Given an array, find the total number of inversions of it. If (i < j) and (A[i] > A[j]), then pair (i, j) is called an inversion of an array A. We need to count all such pairs in the array.

For example,

Input:  A[] = [1, 9, 6, 4, 5]
 
Output: The inversion count is 5
 
There are 5 inversions in the array: (9, 6), (9, 4), (9, 5), (6, 4), (6, 5)

Practice this problem

1. Brute-Force Solution

A simple solution would be for each array element count all elements less than it to its right and add the count to output. The complexity of this solution is O(n2), where n is the size of the input.

C


Download  Run Code

Output:

The inversion count is 5

Java


Download  Run Code

Output:

The inversion count is 5

Python


Download  Run Code

Output:

The inversion count is 5

2. Using Merge Sort

This is a classic problem that can be solved by merge sort algorithm. Basically, for each array element, count all elements more than it to its left and add the count to the output. This whole magic happens inside the merge function of merge sort.

Let’s consider two subarrays involved in the merge process:

Inversion Count – Step 1
Inversion Count – Step 2
Inversion Count – Step 3
Inversion Count – Step 4
Inversion Count – Step 5
Inversion Count – Step 6

 
The implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

The inversion count is 5

Java


Download  Run Code

Output:

The inversion count is 5

Python


Download  Run Code

Output:

The inversion count is 5

The time complexity of the above solution is O(n.log(n)) (same as that of merge sort algorithm), and the auxiliary space used by the program is O(n).