Counting Inversions using Set in C++ STL


In this tutorial, we will be discussing a program to count inversions using set in C++ STL.

Inversion count is a measure of how near the array is to be completely sorted. If the array is already sorted, the inversion count will be 0.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//returning inversion count
int get_Icount(int arr[],int n){
   multiset<int> set1;
   set1.insert(arr[0]);
   int invcount = 0; //initializing result
   multiset<int>::iterator itset1;
   for (int i=1; i<n; i++){
      set1.insert(arr[i]);
      itset1 = set1.upper_bound(arr[i]);
      invcount += distance(itset1, set1.end());
   }
   return invcount;
}
int main()
{
   int arr[] = {8, 4, 2, 1};
   int n = sizeof(arr)/sizeof(int);
   cout << "Number of inversions count are : "<< get_Icount(arr,n);
   return 0;
}

Output

Number of inversions count are : 6

Updated on: 16-Mar-2020

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements