Skip to the content.

22. Quick Sort

Back to the index

Pick a pivot, partition the array into smaller and larger items, then sort both sides. O(n log n) on average, in place, and usually the fastest comparison sort in practice.

How it works

Lomuto partition (used here) takes the last item as the pivot. Index i marks the end of the ‘smaller than pivot’ zone. Scan with j; whenever a[j] < pivot, swap it into the zone and grow the zone. Finally swap the pivot into position i: everything left of it is smaller, everything right is greater or equal, and the pivot is in its final sorted spot.

A bad pivot (for example, always the largest item, as on already-sorted input with last-element pivots) gives O(n^2). Random pivots make that very unlikely.

Diagram

graph TD
    q1["range 0..5: 5 2 9 1 6 3, pivot 3 lands at 2"]
    q2["range 0..1: 2 1, pivot 1 lands at 0"]
    q3["range 3..5: 5 6 9, pivot 9 lands at 5"]
    q4["range 3..4: 5 6, pivot 6 lands at 4"]
    q1 -->|left part| q2
    q1 -->|right part| q3
    q3 -->|left part| q4

Step-by-step trace

Input: Sort [5, 2, 9, 1, 6, 3] with last-element pivots. Each row is one partition call, in the order they run.

Call Range lo..hi Subarray before Pivot Pivot final index Whole array after
1 0..5 [5, 2, 9, 1, 6, 3] 3 2 [2, 1, 3, 5, 6, 9]
2 0..1 [2, 1] 1 0 [1, 2, 3, 5, 6, 9]
3 3..5 [5, 6, 9] 9 5 [1, 2, 3, 5, 6, 9]
4 3..4 [5, 6] 6 4 [1, 2, 3, 5, 6, 9]

Result: Sorted: [1, 2, 3, 5, 6, 9].

Complexity

Operation Time Space
Average O(n log n) O(log n) recursion
Worst (bad pivots) O(n^2) O(n) recursion
Stable? no -

Python reference implementation

def quick_sort(a):
    a = list(a)

    def partition(lo, hi):             # Lomuto: last element is the pivot
        pivot = a[hi]
        i = lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        return i

    def sort(lo, hi):
        if lo < hi:
            p = partition(lo, hi)
            sort(lo, p - 1)
            sort(p + 1, hi)

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

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Merge Sort Next: Heap Sort