← Back to Algorithms, page 3

algorithms-0044 · Medium mid

Implement quicksort in place, explain its average and worst cases, and show how pivot choice and duplicates affect it.

Pick a pivot, partition the list so smaller values come before it and the rest after it, then sort both sides. With balanced splits the depth is log n, giving O(n log n) average time; a bad pivot on every step gives O(n^2). A random pivot makes the worst case very unlikely, recursing on the smaller side caps the stack at O(log n), and three-way partitioning fixes slow behaviour on many duplicates. It is not stable.

Full answer

Problem

Sort a list of numbers in place using quicksort.

Example: [10, 7, 8, 9, 1, 5] becomes [1, 5, 7, 8, 9, 10].

Constraints: 0 <= n <= 10^5; values may repeat; input may already be sorted.

Brute force

Insertion sort: O(n^2) on average. Quicksort with the last element as pivot is also O(n^2) on already sorted input, because each partition removes only one element.

Optimal approach

Lomuto partition on nums[lo..hi]:

  1. Choose a random index as pivot and swap it to hi.
  2. i = lo; for each j in lo..hi - 1, if nums[j] < pivot, swap it into position i and increment i.
  3. Swap the pivot into i; it is now in its final place.

Sorting loop: after partitioning, recurse on the smaller side and loop on the larger side. That keeps the recursion depth at O(log n) even in a bad case.

Three-way version (quick_sort_3way in the code): split into less than, equal to and greater than the pivot. The equal group is never processed again, so a list of many equal keys sorts in near-linear time.

Why it works

After partitioning, every element left of the pivot is smaller, every element right of it is at least as large, and the pivot is in its sorted position. Sorting each side independently therefore sorts the whole list, by induction on size.

Average O(n log n): a random pivot lands in the middle half of the values with probability 1/2, so on average the sizes shrink geometrically and the expected depth is O(log n), with O(n) partition work per level. Worst case O(n^2) happens when every pivot is the minimum or maximum.

Duplicates: with two-way Lomuto, a list of all equal values puts everything on one side every time, which is O(n^2). Three-way partitioning avoids that.

Complexity

Average O(n log n), worst O(n^2) time. O(log n) stack with smaller-side recursion. The three-way version in the code builds new lists, so it uses O(n) extra space; the in-place Dutch national flag partition avoids that.

Code

python
import random


def quick_sort(nums, rng=None):
    """In-place quicksort with random pivot and Lomuto partition. Average O(n log n)."""
    rng = rng or random.Random(42)        # fixed seed so runs are repeatable

    def partition(lo, hi):
        p = rng.randint(lo, hi)           # random pivot avoids sorted-input worst case
        nums[p], nums[hi] = nums[hi], nums[p]
        pivot = nums[hi]
        i = lo
        for j in range(lo, hi):
            if nums[j] < pivot:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
        nums[i], nums[hi] = nums[hi], nums[i]
        return i                          # pivot is now in its final position

    def sort(lo, hi):
        while lo < hi:
            p = partition(lo, hi)
            if p - lo < hi - p:           # recurse on the smaller side: O(log n) stack
                sort(lo, p - 1)
                lo = p + 1
            else:
                sort(p + 1, hi)
                hi = p - 1

    sort(0, len(nums) - 1)
    return nums


def quick_sort_3way(nums):
    """Simple, not in place: splits into <, ==, > the pivot. Handles many duplicates well."""
    if len(nums) <= 1:
        return list(nums)
    pivot = nums[len(nums) // 2]
    return (quick_sort_3way([x for x in nums if x < pivot])
            + [x for x in nums if x == pivot]
            + quick_sort_3way([x for x in nums if x > pivot]))


if __name__ == "__main__":
    for f in (quick_sort, quick_sort_3way):
        assert f([10, 7, 8, 9, 1, 5]) == [1, 5, 7, 8, 9, 10]
        assert f([]) == []
        assert f([2]) == [2]
        assert f([3, 3, 3, 1]) == [1, 3, 3, 3]
        assert f(list(range(2000))) == list(range(2000))          # sorted input
        assert f(list(range(2000, 0, -1))) == list(range(1, 2001))
    print("all tests passed")

Save as a44_quick_sort.py and run python3 a44_quick_sort.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty and single-element lists. Already sorted and reverse sorted input of 2000 elements (the random pivot keeps these fast). Many duplicates (use three-way partitioning). The random generator uses a fixed seed, so runs are repeatable.

Quicksort is not stable: partition swaps can move equal elements past each other. Use merge sort or Python's sorted when stability matters.

Pattern

Partition-based divide and conquer. The same partition step powers quickselect (k-th smallest in average O(n)), Dutch national flag (sort colours) and moving all zeros to the end.

python
import random


def quick_sort(nums, rng=None):
    """In-place quicksort with random pivot and Lomuto partition. Average O(n log n)."""
    rng = rng or random.Random(42)        # fixed seed so runs are repeatable

    def partition(lo, hi):
        p = rng.randint(lo, hi)           # random pivot avoids sorted-input worst case
        nums[p], nums[hi] = nums[hi], nums[p]
        pivot = nums[hi]
        i = lo
        for j in range(lo, hi):
            if nums[j] < pivot:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
        nums[i], nums[hi] = nums[hi], nums[i]
        return i                          # pivot is now in its final position

    def sort(lo, hi):
        while lo < hi:
            p = partition(lo, hi)
            if p - lo < hi - p:           # recurse on the smaller side: O(log n) stack
                sort(lo, p - 1)
                lo = p + 1
            else:
                sort(p + 1, hi)
                hi = p - 1

    sort(0, len(nums) - 1)
    return nums


def quick_sort_3way(nums):
    """Simple, not in place: splits into <, ==, > the pivot. Handles many duplicates well."""
    if len(nums) <= 1:
        return list(nums)
    pivot = nums[len(nums) // 2]
    return (quick_sort_3way([x for x in nums if x < pivot])
            + [x for x in nums if x == pivot]
            + quick_sort_3way([x for x in nums if x > pivot]))


if __name__ == "__main__":
    for f in (quick_sort, quick_sort_3way):
        assert f([10, 7, 8, 9, 1, 5]) == [1, 5, 7, 8, 9, 10]
        assert f([]) == []
        assert f([2]) == [2]
        assert f([3, 3, 3, 1]) == [1, 3, 3, 3]
        assert f(list(range(2000))) == list(range(2000))          # sorted input
        assert f(list(range(2000, 0, -1))) == list(range(1, 2001))
    print("all tests passed")

In-place Lomuto quicksort with a seeded random pivot (random.Random(42)) and smaller-side recursion, plus a simple three-way version.

Complexity

Time: Average O(n log n); worst O(n^2). Space: O(log n) stack for the in-place version; O(n) for the list-building three-way version. Introsort, used by many C++ libraries, switches to heapsort when recursion gets too deep, guaranteeing O(n log n).

By level

Fresher: Implements partition and recursion, and explains why a sorted input with a last-element pivot is slow. Should state that quicksort is not stable.

Mid: Uses random pivots, smaller-side recursion and three-way partitioning, and explains average-case reasoning. Tests sorted, reverse sorted and all-equal inputs.

Senior: Compares quicksort, merge sort and introsort in cache behaviour and guarantees, and discusses pivot strategies such as median of three. Explains why introsort exists.

Key points

  • Partition puts the pivot in its final place
  • Average O(n log n), worst O(n^2)
  • Random pivot avoids sorted-input worst case
  • Recurse on the smaller side for O(log n) stack
  • Three-way partition handles duplicates; not stable

Common mistakes

  • Always choosing the first or last element as pivot
  • Claiming quicksort is stable
  • Recursing on both sides and overflowing the stack on bad input
  • Ignoring the all-equal-values worst case

Follow-ups

  • How does quickselect find the k-th smallest element?
  • Why do some libraries use introsort?
  • When would you prefer merge sort over quicksort?

Tips

  • State average and worst case separately
  • Explain the random pivot with a sorted-input example
  • Mention stability

Evaluation rubric

  • Correct partition and recursion
  • Correct complexity discussion
  • Addresses pivot choice and duplicates
  • Notes instability