Reading preferences
Concept

Quick Sort

Choose a pivot and sort the items on each side of it.

quick sort, pivot, partition, sorting

Choose a marker

Imagine choosing one card as a marker. Put smaller cards to its left and larger cards to its right. Cards equal to the marker can stay with it. Now do the same for each side until every group is small.

The marker is the pivot. Partitioning divides the other items according to their comparison with it.

Why use it and where it helps

Quicksort is a useful way to understand partitioning and is often efficient when partitions are balanced. Implementations differ: some rearrange an array in place; this teaching version creates new lists. A poor sequence of pivots can make it much slower, so it is not guaranteed to beat other sorts.

Follow an example

For [4, 1, 3, 2, 3], choose the first card, 4:

smaller [1, 3, 2, 3] | equal [4] | larger []

Sort the smaller group in the same way, keep all equal cards, and join the answers to get [1, 2, 3, 3, 4]. Unlike merge sort, combining these groups does not require a separate ordered merge.

See the reasoning

Follow the example one step at a time

Sort a row by partitioning around pivots. This is a prepared teaching demonstration, not live code execution.

Start

[4, 1, 3, 2, 3]   pivot: 4

This teaching version chooses the first value as its pivot.

Python illustration

def quick_sort(numbers):
    if len(numbers) <= 1:
        return numbers[:]
    pivot = numbers[0]
    smaller = [x for x in numbers if x < pivot]
    equal = [x for x in numbers if x == pivot]
    larger = [x for x in numbers if x > pivot]
    return quick_sort(smaller) + equal + quick_sort(larger)


print(quick_sort([4, 1, 3, 2, 3]))
print(quick_sort([]))

Prepared output — not live execution:

[1, 2, 3, 3, 4]
[]

The example assumes ordinary mutually comparable numbers with consistent ordering; values such as NaN do not satisfy that assumption. It returns a new list. Three groups preserve duplicates, but not every quicksort variant is stable or uses three groups.

Time, space, and common mistakes

For balanced partitions, work is O(n log n). Repeated uneven partitions can take O(n²) time and O(n) recursive depth; already sorted distinct input causes that case with our first-item pivot. Our copied lists can use O(n log n) peak space for balanced calls and O(n²) in the worst case, including pending lists. Python's recursion limit makes large or adversarial inputs unsafe here.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What is a pivot used for?
2. Where do items equal to the pivot go in this example?
3. Can quicksort take quadratic time?
4. Does this example change the original list?

References and further reading