Given an array, count the total number of triplets, which leads to an inversion. If (i < j < k) and (A[i] > A[j] > A[k]), then we can say that triplet (i, j, k) formed an inversion in an array A.

For example,

A Brute-force solution would be to consider each triplet (A[i], A[j], A[k]) in array A by looping through all possible value of i, j and k. If the inversion condition is satisfied by a triplet, then increment the inversion count. The time complexity of this solution is O(n3), 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

Download   Run Code
Output:

The inversion count is 5

Download   Run Code
Output:

The inversion count is 5

Download   Run Code
Output:

The inversion count is 5

We can easily reduce the time complexity of the solution from O(n3) to O(n2). The idea is to consider each element in array arr[j] as the middle element of the triplet. Then the total number of inversions with arr[j] as the middle element is the product of the total number of elements greater than arr[j] with index less than j with the total number of elements smaller than arr[j] with index more than j.
Basically, for each element of the array, we count all elements more than it to its left and all elements less than it to its right and add their product to the result. Following is C, Java, and Python program that demonstrates it:

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

Download   Run Code
Output:

The inversion count is 5

Download   Run Code
Output:

The inversion count is 5

Download   Run Code
Output:

The inversion count is 5

Source