1. Gyanastra
  2. Algorithms
  3. Divide and Conquer: Max-Min, Maximum Subarray, Inversions and Fast Exponentiation
  4. Counting Inversions with Merge Sort
Free lesson, no account needed 4 min read

Algorithms · Divide and Conquer: Max-Min, Maximum Subarray, Inversions and Fast Exponentiation

Counting Inversions with Merge Sort

4.1 Definition

An inversion is a pair (i,j)(i,j) with i<ji<j and A[i]>A[j]A[i] > A[j]. The inversion count measures how far the array is from sorted; it equals the number of adjacent swaps needed by insertion/bubble sort.

4.2 Method

Modify merge sort: during the merge of left half LL and right half RR, when we take an element from RR because it is smaller than the current L[i]L[i], then L[i]L[i] and every remaining element of LL (there are len(L) - i of them) form inversions with that RR element. Add len(L) - i to the count.

T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n\log n)

4.3 Worked example, n=6n = 6

Array: A = [2, 4, 1, 3, 5, 0]. Split into [2,4,1] and [3,5,0].

Left half [2,4,1] → split [2] and [4,1].

  • [4,1] → split [4],[1]; merge: 1 < 4, take 1 from right, remaining left = 1 element (4), add 1. Merged [1,4].
  • Merge [2] with [1,4]: compare 2 vs 1 → take 1, remaining left = 1 (2), add 1. Compare 2 vs 4 → take 2. Take 4. Merged [1,2,4]. Left-half inversions = 1+1=21+1 = 2.

Right half [3,5,0] → split [3] and [5,0].

  • [5,0]: take 0, remaining left = 1, add 1. Merged [0,5].
  • Merge [3] with [0,5]: 3 vs 0 → take 0, remaining left = 1, add 1. 3 vs 5 → take 3. Take 5. Merged [0,3,5]. Right-half inversions = 1+1=21+1 = 2.

Final merge [1,2,4] with [0,3,5]:

StepCompareTakeRemaining in leftAdd
11 vs 003 (1,2,4)3
21 vs 312 (2,4)0
32 vs 321 (4)0
44 vs 331 (4)1
54 vs 5400
6—500

Cross inversions = 3+1=43+1 = 4.

Total =2+2+4=8= 2 + 2 + 4 = 8.

Verification by brute force. Pairs (i,j)(i,j), i<ji<j, with A[i]>A[j]A[i]>A[j]:

  • i=0i=0 (2): j=2j=2 (1) ✓, j=5j=5 (0) ✓ → 2
  • i=1i=1 (4): j=2j=2 (1) ✓, j=3j=3 (3) ✓, j=5j=5 (0) ✓ → 3
  • i=2i=2 (1): j=5j=5 (0) ✓ → 1
  • i=3i=3 (3): j=5j=5 (0) ✓ → 1
  • i=4i=4 (5): j=5j=5 (0) ✓ → 1
  • i=5i=5: none

Total =2+3+1+1+1=8= 2+3+1+1+1 = 8. ✓ Matches.


Pages 1–2 of 2