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.


 Live Demo

using namespace std;
//returning inversion count
int get_Icount(int arr[],int n){
   multiset<int> set1;
   int invcount = 0; //initializing result
   multiset<int>::iterator itset1;
   for (int i=1; i<n; 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;


Number of inversions count are : 6