Merge sort's recurrence and counting inversions
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
An inversion is a pair of items in the wrong order. Checking every pair takes Θ(n²) work, but merge sort can count them while it sorts. Watch the list 6 3 8 1 5 2 7 4 split down to single items and merge back up: each time a merge takes an item from the right piece, every item still waiting on the left forms an inversion with it, so the count jumps by that many at once. Then read the cost off the levels: T(n) = 2T(n/2) + n, which is Θ(n log n). The Software lessons "Sorting" and "Recursion" introduce merge sort and recursive calls, the Maths lesson "Proofs and induction" covers the argument style, and "The master theorem" in this course solves recurrences like this one in general.
Pairs in the wrong order
An inversion is a pair of items in the wrong order: a bigger number before a smaller one. In 6 3 8 1 5 2 7 4, the pair 6, 3 is one. Checking all 28 pairs finds 15, but that takes Θ(n²) work.
a = [6, 3, 8, 1, 5, 2, 7, 4] n = 8 inversion: positions i < j with a[i] > a[j] pairs to check: n(n - 1)/2 = 28 inversions (15): (6,3) (6,1) (6,5) (6,2) (6,4) (3,1) (3,2) (8,1) (8,5) (8,2) (8,7) (8,4) (5,2) (5,4) (7,4) a sorted list has 0; a reversed one has n(n - 1)/2
اقرأ الدرس خطوة بخطوة
Pairs in the wrong order
An inversion is a pair of items in the wrong order: a bigger number before a smaller one. In 6 3 8 1 5 2 7 4, the pair 6, 3 is one. Checking all 28 pairs finds 15, but that takes Θ(n²) work.
a = [6, 3, 8, 1, 5, 2, 7, 4] n = 8 inversion: positions i < j with a[i] > a[j] pairs to check: n(n - 1)/2 = 28 inversions (15): (6,3) (6,1) (6,5) (6,2) (6,4) (3,1) (3,2) (8,1) (8,5) (8,2) (8,7) (8,4) (5,2) (5,4) (7,4) a sorted list has 0; a reversed one has n(n - 1)/2Split down to single items
Merge sort halves the list, then halves each half, until every piece holds one item. For 8 items that takes 3 levels, since log₂ 8 = 3. A single item is already sorted and has no inversions.
sort_count(a): split at h = len(a) // 2 level 0: 1 × 8 (pieces × size) level 1: 2 × 4 (pieces × size) level 2: 4 × 2 (pieces × size) level 3: 8 × 1 (pieces × size) levels below the top: log₂ 8 = 3 base case: len(a) <= 1 returns (a, 0)Merge single items into pairs
Now merge back up. Merging 6 and 3 takes one compare: 3 is smaller, so it goes first, jumping past the 6 still waiting on the left. That is one inversion. Four pairs: 4 compares, 4 inversions.
merge(L, R) with one item each [6] + [3] -> [3,6] inv 1 [8] + [1] -> [1,8] inv 1 [5] + [2] -> [2,5] inv 1 [7] + [4] -> [4,7] inv 1 compares 4 inversions 4Take the smaller front item
Merge 3 6 with 1 8: compare the two front items and take the smaller. 1 comes from the right while 3 and 6 still wait on the left. Both are bigger, so add 2: inv += m - i.
i, j point at the front items of L and R [3,6] + [1,8] take 1 from R waiting 3,6: +2 take 3 from L take 6 from L take 8 from the rest [2,5] + [4,7] take 2 from L take 4 from R waiting 5: +1 take 5 from L take 7 from the rest compares 6 inversions 3Pairs across the middle
The last merge counts pairs that straddle the middle. When 2 is taken, 3, 6, 8 still wait: +3. Then 4 (+2), 5 (+2), 7 (+1). 8 inversions, without checking the 16 cross pairs one by one.
[1,3,6,8] + [2,4,5,7] take 1 from L take 2 from R waiting 3,6,8: +3 take 3 from L take 4 from R waiting 6,8: +2 take 5 from R waiting 6,8: +2 take 6 from L take 7 from R waiting 8: +1 take 8 from the rest compares 7 inversions 8 out = [1,2,3,4,5,6,7,8]Every pair meets once
Each pair of items meets in exactly one merge: the first piece that holds both. So every inversion is counted once, and the levels add up: 4 + 3 + 8 = 15, the same as checking all 28 pairs.
pairs level 4 fours level 3 final merge 8 total 15 (brute force: 15) sort_count([6, 3, 8, 1, 5, 2, 7, 4]) -> ([1, 2, 3, 4, 5, 6, 7, 8], 15)Each level costs at most n
A merge of m items takes at most m − 1 compares, so a whole level costs under n. Here: 4, 6 and 7 compares, each below 8. Sorting n items is two sorts of n/2 plus a merge: T(n) = 2T(n/2) + n.
compares per level (bound: n minus the number of merges) into 4 × 2 4 (≤ 4) into 2 × 4 6 (≤ 6) into 1 × 8 7 (≤ 7) total 17 T(1) = Θ(1), T(n) = 2T(n/2) + Θ(n)Θ(n log n), not Θ(n²)
There are log₂ n levels and each costs at most n, so T(n) = Θ(n log n). Counting adds one addition per item taken, so the inversion count costs Θ(n log n) as well, not the Θ(n²) of checking every pair.
levels × cost per level = log₂ n × n n = 8: 3 × 8 = 24 (used 17) pairs 28 n = 1,000,000: n log₂ n ≈ 19,931,569 pairs n(n - 1)/2 = 499,999,500,000 counting adds O(1) per take: still Θ(n log n)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01How many inversions does the list [3, 1, 2] have?
The pairs in the wrong order are (3, 1) and (3, 2). The pair (1, 2) is in order, so there are 2 inversions.
02Merging L = [1, 3, 6, 8] with R = [2, 4, 5, 7], the items 1, 2 and 3 are already out, so i = 2. The merge now takes 4 from R. How much does inv grow?
6 and 8 are still waiting in L. Both are bigger than 4 and came before it, so each forms an inversion with it: inv += m − i = 4 − 2 = 2. The items already taken from L (1 and 3) are smaller than 4, so they do not count.
03Why does merge sort count each inversion exactly once?
Two items sit in different halves of exactly one merge: the first piece that contains both. Before it they are apart, after it they are in the same sorted piece. So the counts per merge add up to the total.
04Merging two sorted pieces of 4 items each takes at most how many compares?
Each compare places one item, and once one piece runs out the rest are copied with no compares. At most 8 − 1 = 7. The final merge in the figure needs all 7.
05Which recurrence describes merge sort, and what does it solve to?
Two half-size sorts plus a merge that costs at most n. There are log₂ n levels, each costing at most n, so Θ(n log n). T(n) = T(n − 1) + n is the shape of insertion sort's worst case.
المسرد
- Inversion
- A pair of positions i < j where a[i] > a[j]: a bigger item before a smaller one. A sorted list has none.
- Merge
- Combining two sorted lists into one sorted list by repeatedly taking the smaller of their front items.
- Two pointers
- Indexes i and j that walk along L and R during a merge, each pointing at that list's next item.
- Divide and conquer
- Split a problem into smaller copies, solve them recursively, then combine the answers.
- Recurrence
- An equation that gives a function's value at n in terms of smaller inputs, such as T(n) = 2T(n/2) + n.
- Level
- All the pieces of the same size in merge sort's recursion. For n items there are log₂ n levels of merging.
- Θ(n log n)
- Grows like n times log n, up to a constant factor. Also called linearithmic.
الملاحظات والمصادر
- The whole program, runnable in Python 3: def merge(L, R): m, n = len(L), len(R) out, inv = [], 0 i = j = 0 while i < m and j < n: if L[i] <= R[j]: out.append(L[i]) i += 1 else: out.append(R[j]) j += 1 inv += m - i out += L[i:] + R[j:] return out, inv def sort_count(a): if len(a) <= 1: return a, 0 h = len(a) // 2 L, x = sort_count(a[:h]) R, y = sort_count(a[h:]) out, z = merge(L, R) return out, x + y + z print(sort_count([6, 3, 8, 1, 5, 2, 7, 4])) # ([1, 2, 3, 4, 5, 6, 7, 8], 15)
- The card shows the loop of merge(); the whole runnable function, with sort_count, is in the lesson text. The slices a[:h] and a[h:] copy the list, which costs O(n) per level and does not change the Θ(n log n) total.
- L[i] <= R[j] takes the left item on a tie, so equal items are never counted as an inversion (they are not in the wrong order) and the sort stays stable.
- Merging pieces of s and s items takes at most 2s − 1 compares: each compare places one item, and the last item needs none. This example hits that maximum on every level: 4, 6 and 7 compares.
- The figure uses n = 8, a power of 2, so every split is even. For other n the halves differ by one, and the recurrence is T(n) = T(⌈n/2⌉) + T(⌊n/2⌋) + Θ(n), which is still Θ(n log n).
- The code is real Python 3: sort_count([6, 3, 8, 1, 5, 2, 7, 4]) returns ([1, 2, 3, 4, 5, 6, 7, 8], 15).
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 3: Sorting
- Sedgewick and Wayne, Algorithms 4th ed., §2.2 Mergesort (compares, and the inversions exercise)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §2.3 and Problem 2-4
- Python Standard Library: Common sequence operations (slicing) and list.append
اختبار يتاح بعد الخطوة الأخيرة.