find total number of (i,j) pairs in array such that i<j and a[i]>a[j]

You can count inverted pairs with the algorithm, similar to merge sort, as explained here.

The idea is to merge sort the array while counting, how many inversions were changed on each step.


A different approach is to use an order-statistics tree. You sequentially insert elements of the array into this tree, and after each insertion see, how many elements, preceding the inserted element, are larger than it.

An alternative to order-statistics tree is Indexable skiplist.


Both algorithms have O(N log N) time complexity.

To get approximate number of inversions, O(N) time complexity is possible with some limitations. We can modify Bucket sort in the same manner merge sort was modified.

On "scatter" phase of Bucket sort we should estimate number of elements in buckets for larger elements, while inserting element at the end of some bucket (elements in each bucket remain in original order).

On "sort" phase of Bucket sort we should modify (in the same way) sorting algorithm (insertion sort, most likely). While inserting the element into its proper place, we should count over how many other elements it jumped.

As for limitations, this algorithm works only with numbers (or with objects, easily convertible to numbers), and we should know in advance how these numbers are distributed. So, if we have an array of uniformly distributed integers, this algorithm should work properly.


Such pairs are called number of inversions in an array. It is one measure of how close the array is to being sorted. You can modify merge sort to efficiently count the number of inversions in O(nlogn) time. Refer to this for details.