Inversions

This algorithm finds the number of inversions in a given permutation. We are looking for the number of pairs (a,b) where a > b and is before b. The solution bases on merge sort technique.

Input

n
a(1) a(2) ... a(n)

n – number of elements in a permutation
a(i) – cardinal number between 1 and n

Sample input

6
4 3 1 6 5 2

Output

The number of inversions.

Complexity

In a naive solution we would have to compare each value with all the other on the right, so the complexity would be O(n²). Using merge sort technique we gain complexity O(nlogn).

Source code