Algorithm 2 Count Inversions

Input: An array A[1..n]A[1..n] representing a sequence of nn elements.

Output: The number of inversions in AA .

1: // return the number of inversions in A[p..r]A[p..r] and merge sort A[p..r]A[p..r] .

2:procedure MergeCount(A,p,rA, p, r)

3:if prp \ge r then

4:return 00

5:end if

6:q=(p+r)/2q = \lfloor(p + r)/2\rfloor

7:left=left = MergeCount(A,p,qA, p, q)

8:right=right = MergeCount(A,q+1,rA, q + 1, r)

9:cross=cross = Merge(A,p,q,rA, p, q, r)

10:return left+right+crossleft + right + cross

11:end procedure

12:

13: // merge two subarrays and count the inversion across two subarrays

14:procedure Merge(A,p,q,rA, p, q, r)

15:n1=qp+1n_1 = q - p + 1

16:n2=rqn_2 = r - q

17:Let L[1..n1+1]L[1..n_1 + 1] and R[1..n2+1]R[1..n_2 + 1] be two new arrays.

18:for i=1i = 1 to n1n_1 do

19:L[i]=A[p+i1]L[i] = A[p + i - 1]

20:end for

21:for j=1j = 1 to n2n_2 do

22:R[j]=A[q+j]R[j] = A[q + j]

23:end for

24:L[n1+1]=L[n_1 + 1] = \infty

25:R[n2+1]=R[n_2 + 1] = \infty

26:i=1i = 1

27:j=1j = 1

28:count=0count = 0 // the number of inversions

29:for k=pk = p to rr do

30:if L[i]R[j]L[i] \le R[j] then

31:A[k]=L[i]A[k] = L[i]

32:i=i+1i = i + 1

33:else

34:count=count+n1i+1count = count + n_1 - i + 1

35:A[k]=R[j]A[k] = R[j]

36:j=j+1j = j + 1

37:end if

38:end for

39:return countcount

40:end procedure

41:

42:MergeCount(A,1,nA, 1, n)