Algorithm 2 Count Inversions
Input: An array representing a sequence of elements.
Output: The number of inversions in .
1: // return the number of inversions in and merge sort .
2:procedure MergeCount()
3:if then
4:return
5:end if
6:
7: MergeCount()
8: MergeCount()
9: Merge()
10:return
11:end procedure
12:
13: // merge two subarrays and count the inversion across two subarrays
14:procedure Merge()
15:
16:
17:Let and be two new arrays.
18:for to do
19:
20:end for
21:for to do
22:
23:end for
24:
25:
26:
27:
28: // the number of inversions
29:for to do
30:if then
31:
32:
33:else
34:
35:
36:
37:end if
38:end for
39:return
40:end procedure
41:
42:MergeCount()