/utils

Quicksort

Pick a pivot, split the rest into smaller and larger values, and sort both parts recursively. Fast on average. The in-place version needs almost no extra memory.

SolvesSorting

best
O(n log n)
average
O(n log n)
worst
O(n^2)
space
O(log n)

Quicksort picks a pivot, moves smaller values before it and larger values after it, and sorts both sides the same way [1].

Every pivot is the median of its segment, so each split is even. That gives log₂ n levels of n comparisons: O(n log n). Here: 10 comparisons.

10517263342546

pivot = —

1def quicksort(a):2    if len(a) <= 1:3        return a4    pivot = a[-1]5    # two new lists: extra memory on every call6    smaller = []7    larger = []8    for x in a[:-1]:9        if x < pivot:10            smaller.append(x)11        else:12            larger.append(x)13    left = quicksort(smaller)14    right = quicksort(larger)15    return left + [pivot] + right
1 / 33

len(a) = 7: split it.

comparisons
0
copies
0

How it works

  1. If the list has at most one element, it is sorted.
  2. Take the last element as pivot.
  3. Partition: compare every other element with pivot. Smaller ones go left, the rest go right. The pivot now sits at its final position.
  4. Sort the left and right parts recursively.

Complexity

CaseInputComparisonsTime
Bestpivot = median≈nlog⁡2n\approx n \log_2 nO(nlog⁡n)O(n \log n)
Averagerandom≈1.39 nlog⁡2n\approx 1.39\, n \log_2 nO(nlog⁡n)O(n \log n)
Worstsorted (last = max)n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)

Each level of recursion compares O(n)O(n) elements. Even splits give log⁡2n\log_2 n levels. The worst splits give nn levels [2].

Implementations

Both use the same pivot rule, so they split the same way on best and worst inputs.

  • Simple builds two new lists per call and joins them. Every level copies all nn values: O(n)O(n) extra memory per level.
  • In-place (Lomuto partition) keeps a[low..i-1] < pivot and swaps each smaller value to index i. It copies nothing. The only extra memory is the recursion stack, O(log⁡n)O(\log n) on average.

Pitfalls

  • A fixed pivot (first or last element) makes sorted input the worst case. Real implementations pick a random pivot or the median of three.
  • All keys equal is also a worst case. Every value goes to the right part, so the splits are as uneven as on sorted input. A three-way partition fixes this.
  • Quicksort is not stable: equal values can change order.

Related

References

  1. C. A. R. Hoare, “Quicksort,” The Computer Journal, vol. 5, no. 1, pp. 10–16, 1962. doi.org/10.1093/comjnl/5.1.10
  2. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.

Full bibliography