Quicksort and quickselect: partitions and pivots
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Quicksort sorts by splitting. It picks one item, the pivot, and moves every item that is not bigger to its left and every bigger one to its right. The pivot is then in its final place, and each side is sorted the same way. Watch Lomuto's partition run on the list 6 2 8 1 5 9 4, prove it correct with a loop invariant, then see the cost swing from 11 compares to 21 when the input is already sorted, and how a random pivot fixes that on average. Quickselect reuses the same partition but keeps only one side, so it finds the k-th smallest item in expected linear time. The Software lessons "Sorting" and "Recursion" introduce sorting and recursive calls, the Maths lesson "Proofs and induction" covers the proof style, and "Merge sort's recurrence and counting inversions" in this course is the other divide and conquer sort.
Split around a pivot
Quicksort sorts a list by splitting it. Pick one item, the pivot. Move every item that is not bigger to its left and every bigger one to its right. Now the pivot sits in its final place. Then sort each side the same way.
a = [6, 2, 8, 1, 5, 9, 4] (n = 7)
def partition(a, lo, hi):
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
def quicksort(a, lo, hi):
if lo < hi:
p = partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
quicksort(a, 0, len(a) - 1)
a -> [1, 2, 4, 5, 6, 8, 9]اقرأ الدرس خطوة بخطوة
Split around a pivot
Quicksort sorts a list by splitting it. Pick one item, the pivot. Move every item that is not bigger to its left and every bigger one to its right. Now the pivot sits in its final place. Then sort each side the same way.
a = [6, 2, 8, 1, 5, 9, 4] (n = 7) def partition(a, lo, hi): pivot = a[hi] i = lo - 1 for j in range(lo, hi): if a[j] <= pivot: i += 1 a[i], a[j] = a[j], a[i] a[i+1], a[hi] = a[hi], a[i+1] return i + 1 def quicksort(a, lo, hi): if lo < hi: p = partition(a, lo, hi) quicksort(a, lo, p - 1) quicksort(a, p + 1, hi) quicksort(a, 0, len(a) - 1) a -> [1, 2, 4, 5, 6, 8, 9]The last item is the pivot
partition(a, lo, hi) works on the slice from index lo to hi, here 0 to 6. The last item, 4, is the pivot. A boundary i starts just left of the slice, at −1: no item is known to be small yet.
partition(a, 0, 6) pivot = a[6] = 4 i = 0 - 1 = -1 i marks the end of the "at most pivot" zone j will scan a[0] .. a[5]Scan: small items go left
j walks from lo to hi − 1, comparing each item with the pivot. 6 is bigger: leave it. 2 is not: move i one step right, then swap a[i] and a[j]. Same for 1. After 6 compares, 2 and 1 sit on the left.
j a[j] <= 4? then 0 6 no leave 1 2 yes i = 0, swap a[0], a[1] -> [2, 6, 8, 1, 5, 9, 4] 2 8 no leave 3 1 yes i = 1, swap a[1], a[3] -> [2, 1, 8, 6, 5, 9, 4] 4 5 no leave 5 9 no leave 6 compares, 2 swaps; i = 1Drop the pivot in place
The loop ends. a[0..1] holds items at most 4; a[2..5] holds bigger ones. One last swap moves the pivot to index i + 1 = 2. partition returns 2, which is exactly where 4 belongs in the sorted list.
a[i+1], a[hi] = a[hi], a[i+1] (swap a[2], a[6]) a = [2, 1, 4, 6, 5, 9, 8] return 2 sorted: [1, 2, 4, 5, 6, 8, 9] -> 4 is at index 2 there tooWhy partition is correct
The proof is a loop invariant. Before each pass, a[lo..i] ≤ pivot and a[i+1..j−1] > pivot. It holds at the start, when both zones are empty, and each pass keeps it. At the end j = hi, so every item is on the right side.
invariant, at each test of the for loop: a[lo .. i] <= pivot a[i+1 .. j-1] > pivot a[hi] == pivot start: i = lo - 1, j = lo -> both zones empty keep: a[j] > pivot -> the > zone grows by one a[j] <= pivot -> i += 1, swap: the <= zone grows end: j = hi -> the swap puts the pivot betweenRecurse on each side
quicksort calls itself on the two sides, a[0..1] and a[3..6]. Each call partitions its slice and fixes one more pivot. A slice of 0 or 1 items is already sorted. The whole list is sorted after 11 compares.
quicksort(a, 0, 6) partition -> p = 2 6 compares quicksort(a, 0, 1) pivot 1 -> p = 0 1 compare quicksort(a, 3, 6) pivot 8 -> p = 5 3 compares quicksort(a, 3, 4) pivot 5 -> p = 3 1 compare total 11 compares a = [1, 2, 4, 5, 6, 8, 9] balanced splits: T(n) = 2T(n/2) + Θ(n) = Θ(n log n)Sorted input: the worst case
Now sort the sorted list. The last item is always the biggest, so each split puts every other item on one side. Compares: 6 + 5 + 4 + 3 + 2 + 1 = 21, which is n(n − 1)/2: Θ(n²).
a = [1, 2, 4, 5, 6, 8, 9] partition sizes 7, 6, 5, 4, 3, 2: compares 6+5+4+3+2+1 total 21 = 7·6/2 T(n) = T(n - 1) + Θ(n) = Θ(n²) recursion depth n - 1 = 6 (not log n)Pick the pivot at random
The fix: pick the pivot at random and swap it to the end first. Here randint picks index 3, the 5: a 3 and 3 split. Random pivots give expected Θ(n log n) compares on every input, 13.5 on average for n = 7.
import random def random_partition(a, lo, hi): r = random.randint(lo, hi) a[r], a[hi] = a[hi], a[r] return partition(a, lo, hi) random.randint(0, 6) -> 3 (say) swap a[3], a[6] -> [1, 2, 4, 9, 6, 8, 5] partition -> p = 3 6 compares, split 3 | 3 expected compares, n = 7: 2(n+1)H(n) - 4n = 13.49 about 2n ln n for large n (vs n(n-1)/2 = 21 at worst)Quickselect keeps one side
Quickselect finds the k-th smallest without sorting. Want k = 3. The first pivot lands at 2, so the answer lies to its right: drop the left side. Two more partitions put 5 at index 3. With random pivots, keeping one side costs expected Θ(n).
def quickselect(a, lo, hi, k): p = partition(a, lo, hi) if k < p: return quickselect(a, lo, p - 1, k) if k > p: return quickselect(a, p + 1, hi, k) return a[p] quickselect([6, 2, 8, 1, 5, 9, 4], 0, 6, 3) partition(0, 6): p = 2 < 3 -> keep 3..6 6 compares partition(3, 6): p = 5 > 3 -> keep 3..4 3 compares partition(3, 4): p = 3 = k -> return 5 1 compare 10 compares; a[0..1] = [2, 1] is never sorted
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Lomuto's partition runs on [3, 7, 1, 5] with pivot 5 (the last item). At which index does 5 end up?
Two items, 3 and 1, are at most 5, so they fill indexes 0 and 1. The pivot goes right after them, at index 2, which is exactly its place in the sorted list [1, 3, 5, 7].
02Which statement is the loop invariant of Lomuto's partition, true before each pass of the for loop?
Two zones grow as j scans: the "at most pivot" zone ends at i and the "bigger" zone runs from i + 1 to j − 1. When j reaches hi every item is in one of the zones, so the final swap puts the pivot between them.
03Quicksort with the last item as pivot sorts an already sorted list of 7 items. How many compares does it make?
Each pivot is the biggest item, so one side is empty and the other has all the rest. The partitions make 6 + 5 + 4 + 3 + 2 + 1 = 21 = 7·6/2 compares: the Θ(n²) worst case.
04Why does choosing the pivot at random help?
A random pivot can still be unlucky, but the expectation over the pivot choices is about 2n ln n compares whatever the input. The worst case is still Θ(n²), it just becomes very unlikely.
05Quickselect looks for index k = 3 and the first partition returns p = 5. What does it do next?
Everything left of index 5 is at most the pivot, so the item that belongs at index 3 is on the left. Quickselect keeps only that side, which is why its expected cost is Θ(n) instead of Θ(n log n).
المسرد
- Pivot
- The item a partition splits around. After the partition it sits in its final sorted place.
- Partition
- Rearranging a slice so items at most the pivot come first, then the pivot, then bigger items. Takes m − 1 compares for m items.
- Lomuto partition
- The partition scheme in CLRS chapter 7: the last item is the pivot, a boundary i ends the small zone and j scans left to right.
- Loop invariant
- A statement that is true before every pass of a loop. Showing it starts true, stays true and implies the goal at the end proves the loop correct.
- Randomized algorithm
- An algorithm that makes random choices, such as a random pivot. Its cost is stated as an expectation over those choices.
- Quickselect
- Hoare's selection algorithm: partition, then recurse only into the side that holds index k. Expected Θ(n) with random pivots.
- In place
- Sorting inside the list itself, using only a little extra memory. Quicksort sorts in place; it is not stable.
الملاحظات والمصادر
- The whole program, runnable in Python 3: def partition(a, lo, hi): pivot = a[hi] i = lo - 1 for j in range(lo, hi): if a[j] <= pivot: i += 1 a[i], a[j] = a[j], a[i] a[i+1], a[hi] = a[hi], a[i+1] return i + 1 def quicksort(a, lo, hi): if lo < hi: p = partition(a, lo, hi) quicksort(a, lo, p - 1) quicksort(a, p + 1, hi) import random def random_partition(a, lo, hi): r = random.randint(lo, hi) a[r], a[hi] = a[hi], a[r] return partition(a, lo, hi) def quickselect(a, lo, hi, k): p = partition(a, lo, hi) if k < p: return quickselect(a, lo, p - 1, k) if k > p: return quickselect(a, p + 1, hi, k) return a[p] a = [6, 2, 8, 1, 5, 9, 4] quicksort(a, 0, len(a) - 1) print(a) # [1, 2, 4, 5, 6, 8, 9] print(quickselect([6, 2, 8, 1, 5, 9, 4], 0, 6, 3)) # 5
- The figure uses Lomuto's partition, the version in CLRS chapter 7: the last item is the pivot and items equal to it go left. Hoare's original scheme scans from both ends and does fewer swaps; Sedgewick and Wayne use a variant of it.
- A compare is one run of the test a[j] <= pivot. A partition of m items makes m − 1 compares. The 11, 21 and 10 in the figure are real counts from running the Python code.
- With a random pivot at every call, the exact expected number of compares on n distinct items is 2(n + 1)H(n) − 4n, where H(n) = 1 + 1/2 + ... + 1/n. For n = 7 that is 13.49. Sedgewick and Wayne state it as about 2n ln n.
- In the random step the pivot index is fixed at 3 so the figure is repeatable; random.randint(lo, hi) can return any index from lo to hi with equal chance.
- Quickselect with random pivots runs in expected Θ(n) time (CLRS §9.2), but a run of unlucky pivots still costs Θ(n²). CLRS §9.3 gives a selection algorithm that is Θ(n) in the worst case.
- Quicksort sorts in place but is not stable: equal items can change order. Python's own list.sort is Timsort, a stable merge-based sort.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 7 and §9.2
- Sedgewick and Wayne, Algorithms 4th ed., §2.3 Quicksort
- Sedgewick and Wayne, Algorithms 4th ed., §2.5 Sorting applications (selection, stability)
- MIT 6.046J Introduction to Algorithms (Fall 2005), Lecture 4: Quicksort, Randomized Algorithms
- MIT 6.046J Design and Analysis of Algorithms (Spring 2015), Recitation 4: Randomized Median
- Quickselect (Hoare's selection algorithm)
- Python Standard Library: random.randint
اختبار يتاح بعد الخطوة الأخيرة.