Intermediate 8 min

Quicksort and partitioning

Quicksort groups elements around a pivot and sorts the remaining groups separately.

How it works

Start by deciding which comparison sends a value to each group. The pivot itself belongs to the middle group and stays there. Recursively order the lower and higher groups, then read lower, equal, higher. The sample code shows partitioning; the calls around it are what make the full sort.

Walk through an example

With pivot 4 and list [5, 1, 4, 2], one three-way partition groups [1, 2], [4], and [5]. Once the smaller and larger groups are sorted, the whole list is sorted.

What to watch for

Repeatedly picking the smallest or largest item can create uneven groups and quadratic work. Three-way partitioning also helps when many keys equal the pivot.

Code example

def partition(a, p):
    return ([x for x in a if x < p],
            [x for x in a if x == p],
            [x for x in a if x > p])

Check your understanding

Which three groups does a three-way partition produce?

See the example and explanation
Worked example
Given [5, 2, 5, 9, 1], pivot 5
Answer [2, 1], [5, 5], [9]

Compare each item with 5 and place it into the lower, equal, or greater group.

Open practice problem
Next lessonHeaps and priority queues