Count inversions in an array | Set 3 (Using BIT)

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in the 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
Explanation: Given array has six inversions:
(8,4), (4,2), (8,2), (8,1), (4,1), (2,1).     


Input: arr[] = {3, 1, 2}
Output: 2
Explanation: Given array has two inversions:
(3,1), (3,2).

We strongly recommend that you click here and practice it, before moving on to the solution.

We have already discussed below methods to solve inversion count:



  1. Naive and Modified Merge Sort
  2. Using AVL Tree

We recommend you to refer Binary Indexed Tree (BIT) before further reading this post.

Solution using BIT of size Θ(maxElement):

Better solution using BIT of size Θ(n):

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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.





Article Tags :