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.

`// A STL Set based approach for inversion count ` `#include<bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Returns inversion count in arr[0..n-1] ` `int` `getInvCount(` `int` `arr[],` `int` `n) ` `{ ` ` ` `// Create an empty set and insert first element in it ` ` ` `multiset<` `int` `> set1; ` ` ` `set1.insert(arr[0]); ` ` ` ` ` `int` `invcount = 0; ` `// Initialize result ` ` ` ` ` `multiset<` `int` `>::iterator itset1; ` `// Iterator for the set ` ` ` ` ` `// Traverse all elements starting from second ` ` ` `for` `(` `int` `i=1; i<n; i++) ` ` ` `{ ` ` ` `// Insert arr[i] in set (Note that set maintains ` ` ` `// sorted order) ` ` ` `set1.insert(arr[i]); ` ` ` ` ` `// Set the iterator to first greater element than arr[i] ` ` ` `// in set (Note that set stores arr[0],.., arr[i-1] ` ` ` `itset1 = set1.upper_bound(arr[i]); ` ` ` ` ` `// Get distance of first greater element from end ` ` ` `// and this distance is count of greater elements ` ` ` `// on left side of arr[i] ` ` ` `invcount += distance(itset1, set1.end()); ` ` ` `} ` ` ` ` ` `return` `invcount; ` `} ` ` ` `// Driver program to test above ` `int` `main() ` `{ ` ` ` `int` `arr[] = {8, 4, 2, 1}; ` ` ` `int` `n = ` `sizeof` `(arr)/` `sizeof` `(` `int` `); ` ` ` `cout << ` `"Number of inversions count are : "` ` ` `<< getInvCount(arr,n); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

Output:

Number of inversions count are : 6

Note that the worst case time complexity of above implementation is O(n^{2}) 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.

This article is contributed by **Abhiraj Smit**. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Counting inversions in an array using segment tree
- Counting inversions in all subarrays of given size
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Count inversions in an array | Set 2 (Using Self-Balancing BST)
- Count inversions in an array | Set 3 (Using BIT)
- Time complexity of insertion sort when there are O(n) inversions?
- Count Inversions of size three in a given array
- Number of permutation with K inversions
- Subarray Inversions
- Count inversions of size k in a given array
- Significant Inversions in an Array
- Check if the count of inversions of two given types on an Array are equal or not
- Count number of unique Triangles using STL | Set 1 (Using set)
- Counting cross lines in an array
- Dijkstra’s shortest path algorithm using set in STL
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Sorting Array Elements By Frequency | Set 3 (Using STL)
- Binary Tree to Binary Search Tree Conversion using STL set
- Count smaller elements on right side using Set in C++ STL