![]() |
VOOZH | about |
Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum.
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
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)
Traverse through the array, and for every index, find the number of smaller elements on it's right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum.
Number of inversions are 5
Please refer complete article on Count Inversions in an array | Set 1 (Using Merge Sort) for more details!