How quicksort recurses after a partition

Short answer: Quicksort partitions a slice around a pivot and sorts the two sides. With Lomuto’s partition the pivot ends at its final index and is excluded from both recursive calls. With Hoare’s partition the cut index is only a boundary between small keys and large keys, and the pivot may sit on either side of it. Average cost with a random pivot is O(n log n). A consistently bad pivot is Θ(n²).


What the problem actually asks

Partition rearranges a slice so that keys on the left of a cut are at most the pivot and keys on the right are at least the pivot. The recursive calls are then independent. Which index is passed to those calls depends on which partition was used. Treating Hoare’s returned index as the pivot’s final home drops keys or loops.

The pivot also decides the cost. A pivot that always lands at the end of the slice leaves one side empty and the other side only one item shorter. That recursion is Θ(n²). A pivot near the middle splits the work into the same recurrence as mergesort.


What the algorithm guarantees

After a correct partition, each side is a smaller independent sort. Random pivots give an expected O(n log n) comparisons; the constant for a uniformly random pivot is about 1.386 n log₂ n. The worst case is Θ(n²). Extra memory is the recursion stack. Recursing into the smaller side first, and looping on the larger side, keeps that stack at O(log n) even on a bad split. The usual in-place partitions are unstable.

Lomuto walks one index and swaps keys greater than the pivot to the right. When it finishes, the pivot occupies its final rank and both sides exclude that index. Hoare walks two indices inward and swaps a large left key with a small right key. When they cross, every key up through the crossing is at most every key after it, and the pivot value itself need not sit at the crossing.


The working steps

  1. On a slice of fewer than two items, return.
  2. Choose a pivot. A random index, or a median of the first, middle, and last items, avoids the sorted-input degeneration of always picking one end.
  3. Lomuto: swap the pivot to the end, scan the slice, swap each smaller key into the growing left part, then swap the pivot into the boundary. Recurse on the two open sides and skip the pivot index.
  4. Hoare: scan from both ends, swap inversions relative to the pivot value, and stop when the indices cross. Recurse on the left slice through the crossing and the right slice after it. Include every index in exactly one side.
  5. Sort the smaller side first, then continue with the larger side in the same frame, so the stack depth tracks the smaller side.

This is an in-place comparison sort. It does not provide a stable order, and the O(n log n) figure is an expectation unless the recursion is capped and a heap finishes the deep slices. That cap is introsort.


Approaches that look simpler and fail

Approach Why it fails when the partition’s cut is misread
Exclude Hoare’s cut index as if the pivot were finished The pivot may lie strictly inside one side. Dropping the cut index loses an unsorted key, and a side that does not shrink loops.
Always pivot on the first item A sorted or nearly sorted array produces empty sides. The cost becomes Θ(n²) on the input people try first.
Assume the average bound is a worst-case bound Adversarial or already ordered pivots realize the quadratic recursion. The expectation needs random pivots or an equivalent shuffle.
Partition equals to both sides at random and call the sort stable Equal keys are swapped across the pivot. Their original order is gone.

A hard O(n log n) ceiling on the same partition belongs to introsort. A stable n log n sort belongs to mergesort. Finding one rank, rather than sorting, is quickselect and reuses a partition that places the pivot.


A working example

The Bash script and the Python script quicksort with Lomuto’s partition, then finish the smaller side before the larger side. Both print 1 2 3 4 4.

a=(4 2 4 3 1)
rec() {
  local lo=$1 hi=$2 pivot i j t
  while (( hi - lo >= 2 )); do
    pivot=${a[hi-1]}
    i=$lo
    for ((j=lo; j<hi-1; j++)); do
      if (( a[j] < pivot )); then
        t=${a[i]}; a[i]=${a[j]}; a[j]=$t
        i=$((i+1))
      fi
    done
    t=${a[i]}; a[i]=${a[hi-1]}; a[hi-1]=$t
    if (( i - lo < hi - (i + 1) )); then
      rec "$lo" "$i"
      lo=$((i+1))
    else
      rec "$((i+1))" "$hi"
      hi=$i
    fi
  done
}
rec 0 ${#a[@]}
echo "${a[*]}"
def quicksort(a):
    def rec(lo, hi):
        while hi - lo >= 2:
            pivot = a[hi - 1]
            i = lo
            for j in range(lo, hi - 1):
                if a[j] < pivot:
                    a[i], a[j] = a[j], a[i]
                    i += 1
            a[i], a[hi - 1] = a[hi - 1], a[i]
            if i - lo < hi - (i + 1):
                rec(lo, i)
                lo = i + 1
            else:
                rec(i + 1, hi)
                hi = i
    rec(0, len(a))
    return a

a = quicksort([4, 2, 4, 3, 1])
assert a == sorted([4, 2, 4, 3, 1])
print(*a)

Where it is used

Quicksort is the partition sort inside introsort and the historical implementation of C qsort. The average bound is n log n; a bad pivot makes it quadratic, which is why the production sort caps the depth with a heap. A stable sort does not use this partition.


When you can drop this algorithm

Drop plain quicksort when the caller needs a worst-case n log n proof or a stable result. Use introsort for the first and mergesort or timsort for the second. Keep quicksort when average speed and an in-place partition are the requirements, and when the pivot is random or otherwise kept off the end of a sorted slice.


Why this stays published

We publish this so a search for quicksort returns the difference between a partition that places the pivot and a partition that only returns a cut. Quicksort’s average cost is n log n with a random pivot, and Hoare’s cut is a boundary the pivot may sit on either side of.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *