Skip to content
Codescope

Quicksort

Partition around a pivot, and the input that makes it O(n²).

deep12 min8 steps

Before you start

Quicksort rests on one move called **partitioning**: pick a value (the *pivot*), then rearrange the array so everything smaller sits to its left and everything larger sits to its right.

After one partition the pivot is in its **final** position — it will never move again. And the two sides are independent subproblems, so quicksort calls itself on each.

Where merge sort guarantees O(n log n) by always splitting evenly, quicksort *gambles*: the split is only even if the pivot happens to be near the median. When that bet fails, it degrades badly — and this lesson shows exactly when and why.

quicksort

pivot = last element
array
7
2
1
6
8
5
4
pivot

Pivot is 4. One pass will put everything smaller left, larger right.

Step 1 of 8. Pick a pivot. The array is unsorted. This implementation takes the **last element** as the pivot — `4` here. (Real implementations pick more carefully; we'll see why shortly.) The goal of the next pass: get every value less than 4 to the left of it, every value greater to the right. Not sorted — just partitioned.

01 / 08

Step 01 / 08

Pick a pivot

The array is unsorted. This implementation takes the **last element** as the pivot — 4 here. (Real implementations pick more carefully; we'll see why shortly.)

The goal of the next pass: get every value less than 4 to the left of it, every value greater to the right. Not sorted — just partitioned.

quicksort.cC
void quicksort(int a[], int lo, int hi) {    if (lo >= hi) return;    int p = partition(a, lo, hi);   /* pivot lands at p */    quicksort(a, lo,    p - 1);     /* everything smaller */    quicksort(a, p + 1, hi);        /* everything larger  */}int partition(int a[], int lo, int hi) {    int pivot = a[hi];              /* last element as pivot */    int i = lo - 1;                 /* boundary of "smaller" */    for (int j = lo; j < hi; j++) {        if (a[j] < pivot) {            i++;            swap(&a[i], &a[j]);        }    }    swap(&a[i + 1], &a[hi]);        /* pivot into position */    return i + 1;}