This is my implementation of the counting inversions algorithm for Stanford’s MOOC course on algorithm design and analysis. One application of this algorithm is the analysis of rankings, where a numer of websites make use of a technique known as collaborative filtering to try to match your preferences for books, movies, restaurants, etc. with those of other people in their database. Once a website has identified people with similar taste to you, it can recommend new things that these people have liked. Amazon.com’s recommendation engine (“Customers who bought this also bought…”) is a perfect example of this.
First, let’s define what an inversion is. For an array a and indices i < j, i, j form an inversion if a[i] > a[j]. A naive algorithm will make pairwise comparisons of array elements to figure out inversions but this will run in O(n^2) time where n is the size of the input array. We can do better than that by piggybacking on the merge sort algorithm, or to be exact, the merge subroutine in merge sort. The idea is everytime an element from the left subarray is appended to the output, no new inversions are encountered, since that element is smaller than everything remaining in the right subarray. However, if an element from the right subarray is appended to the output, then it is smaller than all the remaining items in the left subarray, hence we increase the number of count of inversions by the number of elements remaining in the left subarray.