Reading history

Quick Sort in C: Partition, Pivot Choice and Complexity

5 min read 1 views

Learn quick sort in C: Lomuto partitioning, recursive sorting, why sorted input causes O(n squared), random pivots, and quickselect.

Quick sort picks one element as a pivot, moves smaller elements to its left and larger ones to its right, and then sorts the two sides recursively. It sorts in place, has excellent cache behaviour and is usually the fastest general-purpose comparison sort on arrays. Its weakness is a bad pivot choice, which this lesson demonstrates and fixes.

In this lesson you will learn

  • How partitioning around a pivot works
  • The Lomuto partition scheme in C
  • A complete recursive quick sort
  • Why sorted input can make quick sort slow
  • How a random pivot avoids the worst case

Partition and Quick Sort in C

#include <stdio.h>

void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }

/* Lomuto partition: last element is the pivot */
int partition(int a[], int lo, int hi) {
    int pivot = a[hi];
    int i = lo - 1;                       /* end of the "smaller" region */
    for (int j = lo; j < hi; j++) {
        if (a[j] < pivot) {
            i++;
            swap(&a[i], &a[j]);
        }
    }
    swap(&a[i + 1], &a[hi]);              /* put pivot between the regions */
    return i + 1;
}

void quick_sort(int a[], int lo, int hi) {
    if (lo < hi) {
        int p = partition(a, lo, hi);     /* a[p] is now in its final place */
        quick_sort(a, lo, p - 1);
        quick_sort(a, p + 1, hi);
    }
}

int main(void) {
    int a[] = {10, 80, 30, 90, 40, 50, 70};
    int n = sizeof a / sizeof a[0];

    int p = partition(a, 0, n - 1);
    printf("After first partition (pivot 70 at index %d): ", p);
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");

    quick_sort(a, 0, n - 1);
    printf("Sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output

After first partition (pivot 70 at index 4): 10 30 40 50 70 90 80 
Sorted: 10 30 40 50 70 80 90
  • partition uses the last element, 70, as the pivot. Index i marks the end of the region of values smaller than the pivot; each smaller value found by j is swapped into that region.
  • Finally the pivot is swapped into position i + 1. After the first partition, 70 is at index 4 and will never move again: everything to its left is smaller and everything to its right is larger.
  • quick_sort then sorts the two sides independently. Unlike merge sort, all the work happens before the recursive calls, and nothing needs merging afterwards.

The Danger of a Bad Pivot

#include <stdio.h>
#include <stdlib.h>

static long comparisons;

void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }

int partition(int a[], int lo, int hi) {
    int pivot = a[hi], i = lo - 1;
    for (int j = lo; j < hi; j++) {
        comparisons++;
        if (a[j] < pivot) swap(&a[++i], &a[j]);
    }
    swap(&a[i + 1], &a[hi]);
    return i + 1;
}

void quick_sort(int a[], int lo, int hi, int randomize) {
    if (lo >= hi) return;
    if (randomize) {                      /* pick a random pivot first */
        int r = lo + rand() % (hi - lo + 1);
        swap(&a[r], &a[hi]);
    }
    int p = partition(a, lo, hi);
    quick_sort(a, lo, p - 1, randomize);
    quick_sort(a, p + 1, hi, randomize);
}

int main(void) {
    enum { N = 2000 };
    static int a[N];
    srand(1);

    for (int i = 0; i < N; i++) a[i] = i;          /* already sorted input */
    comparisons = 0;
    quick_sort(a, 0, N - 1, 0);
    printf("Sorted input, last-element pivot: %ld comparisons\n", comparisons);

    for (int i = 0; i < N; i++) a[i] = i;
    comparisons = 0;
    quick_sort(a, 0, N - 1, 1);
    printf("Sorted input, random pivot:       %ld comparisons\n", comparisons);
    return 0;
}

Output

Sorted input, last-element pivot: 1999000 comparisons
Sorted input, random pivot:       23829 comparisons
  • On already sorted input, the last element is always the largest, so every partition splits off just one element. The recursion becomes n levels deep and makes n(n − 1)/2 comparisons, which is 1,999,000 for 2,000 items: the O(n²) worst case.
  • Swapping a randomly chosen element into the pivot position makes balanced splits very likely whatever the input order, bringing the count down to about 24,000, close to the expected n log n behaviour.
  • Other common fixes are the median of three (median of the first, middle and last elements) and switching to heap sort if recursion gets too deep, which is what introsort does.

Complexity

CaseTimeWhen
Best / averageO(n log n)Pivots split the array roughly in half
WorstO(n²)Pivot is always the smallest or largest
Extra spaceO(log n) averageFor the recursion stack
StableNoPartition swaps can reorder equal values

Common Mistakes

  1. Always using the first or last element as the pivot on data that may already be sorted.
  2. Recursing on the wrong ranges, such as including the pivot again, which can cause infinite recursion.
  3. Ignoring many duplicate values; with all-equal input, Lomuto partitioning also degrades. Three-way partitioning handles duplicates well.
  4. Assuming quick sort is stable.

Practice Exercises

Exercise 1. Partition {9, 3, 7, 1, 5} with the last element as the pivot. Where does 5 end up?

Show answer

3 and 1 are smaller than 5, so the result is {3, 1, 5, 9, 7} and 5 lands at index 2.

Exercise 2. Use quick sort’s partition to find the k-th smallest element without fully sorting (quickselect).

Show answer
int quickselect(int a[], int lo, int hi, int k) {   /* k is 0-based */
    int p = partition(a, lo, hi);
    if (p == k) return a[p];
    return (k < p) ? quickselect(a, lo, p - 1, k)
                   : quickselect(a, p + 1, hi, k);
}

It only recurses into one side, so the average time is O(n).

Frequently Asked Questions

Why is quick sort fast in practice if its worst case is O(n²)?

With a good pivot strategy the worst case is extremely unlikely, and quick sort works on contiguous memory with simple inner loops, which makes very good use of the CPU cache.

What is the difference between Lomuto and Hoare partitioning?

Lomuto, used here, is easier to understand. Hoare’s original scheme uses two indexes moving towards each other and usually makes about three times fewer swaps.

Summary

  • Quick sort partitions around a pivot, then sorts each side.
  • Average O(n log n), in place, but not stable.
  • Bad pivots on sorted input cause O(n²); random or median-of-three pivots fix it.
  • Partitioning also powers quickselect for finding the k-th smallest value.

Next: Binary Trees in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *