VOOZH about

URL: https://www.geeksforgeeks.org/cpp/counting-inversions-using-set-in-c-stl/

⇱ Counting Inversions using Set in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counting Inversions using Set in C++ STL

Last Updated : 23 Jul, 2025
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
 Two elements a[i] and a[j] form an inversion if 
 a[i] > a[j] and i < j. For simplicity, we may 
 assume that all elements are unique.

 Example:
 Input: arr[] = {8, 4, 2, 1}
 Output: 6
 Given array has six inversions (8,4), (4,2),
 (8,2), (8,1), (4,1), (2,1). 
We have already discussed below approaches. 1) Naive and Merge Sort based approaches. 2) AVL Tree based approach. In this post an easy implementation of approach 2 using Set in C++ STL is discussed.
1) Create an empty Set in C++ STL (Note that a Set in C++ STL is 
 implemented using Self-Balancing Binary Search Tree). And insert
 first element of array into the set.

2) Initialize inversion count as 0.

3) Iterate from 1 to n-1 and do following for every element in arr[i]
 a) Insert arr[i] into the set.
 b) Find the first element greater than arr[i] in set
 using upper_bound() defined Set STL.
 c) Find distance of above found element from last element in set
 and add this distance to inversion count.

4) Return inversion count.
Output:
Number of inversions count are : 6
Note that the worst case time complexity of above implementation is O(n2) as distance function in STL takes O(n) time worst case, but this implementation is much simpler than other implementations and would take much less time than Naive method on average.
Comment
Article Tags: