Quick sort in C, visualized step by step
Pick a value as the pivot, move every smaller value to its left and leave the rest on its right: the pivot lands exactly where it belongs. Then do the same to each side.
quick_sort.c
#include <stdio.h>
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];
int i = lo;
for (int j = lo; j < hi; j++)
if (a[j] < pivot)
swap(&a[i++], &a[j]);
swap(&a[i], &a[hi]);
return i;
}
void quick_sort(int a[], int lo, int hi) {
if (lo >= hi) return;
int p = partition(a, lo, hi);
quick_sort(a, lo, p - 1);
quick_sort(a, p + 1, hi);
}
int main(void) {
int a[] = {4, 7, 2, 6, 1, 5};
quick_sort(a, 0, 5);
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}
How Quick sort works
- Take the last value of the range as the pivot.
- j scans left to right; each value smaller than the pivot is swapped into position i, and i moves right.
- After the scan, swap the pivot into position i: smaller values on its left, the rest on its right.
- Sort the parts left and right of the pivot recursively.
What to watch
iEverything left of i is smaller than the pivot: i is the edge of that zone.
Where the pivot landsAfter each partition the pivot sits in its final sorted place and never moves again.
FAQ
What is the time complexity of quick sort?
O(n log n) on average. O(n²) in the worst case: when the pivot is always the largest or smallest value (a sorted input with the last value as pivot), each step removes only one value. A random pivot avoids it.
Is quick sort stable?
No. The long-distance swaps in partitioning can reorder equal values.
Why is quick sort usually faster than merge sort?
It swaps in place with no extra array, and its memory access is more sequential. C's qsort is usually a tuned quick sort.