Divide and Conquer Algorithms
Merge Sort
Binary Search
Comparing rankings
Brute force solution
Divide and conquer
Merging two sorted lists while also counting the number of inversions between them.
Merge-and-Count(A,B)
Maintain a Current pointer into each list, initialized to point to the front elements
Maintain a variable Count for the number of inversions, initialized to 0
While both lists are nonempty:
Let a<sub>i</sub> and b<sub>j</sub> be the elements pointed to by the Cuwent pointer
Append the smaller of these two to the output list
If b<sub>j</sub> is the smaller element then
Increment Count by the number of elements remaining in A
Endif
Advance the Current pointer in the list from which the smaller element was selected.
EndWhile
Once one list is empty, append the remainder of the other list to the output
Return Count and the merged list
The Sort-and-Count algorithm correctly sorts the input list and counts the number of inversions; it runs in O(n log n) time for a list with n elements.
Sort-and-Count(L)
If the list has one element then there are no inversions
Else
Divide the list into two halves:
A contains the first [n/2](ceiling) elements
B contains the remaining [n/2](floor) elements
(r<sub>A</sub>, A) = Sort-and-Count (A)
(r<sub>B</sub>, B) = Sort-and-Count (B)
(r, L) = Merge-and-Count (A, B)
Endif
Return r = r<sub>A</sub> + r<sub>B</sub> + r, and the sorted list L