ENع
→Quicksort and quickselect
الدرس 30 · Greedy and divide and conquer

Quicksort and quickselect: partitions and pivots

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 30 · تفاعلي
01 / 09

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]
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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]
  2. 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]
  3. 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 = 1
  4. Drop 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 too
  5. Why 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 between
  6. Recurse 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)
  7. 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)
  8. 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)
  9. 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

اختبار يتاح بعد الخطوة الأخيرة.