Quick Sort in C and C++
Pick a pivot, move smaller values left and larger right, repeat. Learn why quick sort is fast on average and when it is not.
- Choosing a pivot and partitioning
- Recursing on the two sides
- Average O(n log n) versus worst-case O(n²)
Partition around a pivot
The problem
Quick sort is the algorithm behind many standard library sort functions. It sorts in place without a big extra buffer and is usually very fast, so understanding it explains how real sorting works.
Think of it like this
Quick sort is like organizing a line of people by height around one chosen person, the pivot. Everyone shorter moves to the left, everyone taller to the right, and the pivot now stands exactly where they belong. Then each side does the same, with its own pivot.
pivot = values[high]🧍 Choose one person as the referencevalues[scan] < pivot↔️ Shorter people move to the leftswap(&values[boundary], &values[high])📍 The pivot steps into its final placequick_sort(...) on both sides🔁 Each side repeats with its own pivotQuick sort picks a pivot, partitions the data so smaller values come before it and larger values after it, then sorts each part recursively; it takes O(n log n) time on average.
Important points
partitionuses the last value aspivotand moves smaller values in front ofboundary.- The final
swapputs the pivot atboundary, its correct sorted position. quick_sortthen sorts the parts before and after the pivot; no merge step is needed.- The C++ version uses
std::partitionwith a lambda for the same step.
When to use it
- Fast in-place sorting of arrays.
- Understanding how library sorts such as
std::sortwork. - Partition-based tasks such as finding the k-th smallest value.
When not to use it
- Already sorted data with a naive pivot choice: it degrades to
O(n²). - You need a stable sort or guaranteed
O(n log n): use merge sort orstd::stable_sort.
Quick Sort visualizer
Use Play or Step to follow each comparison and data movement.
C and C++ code examples
#include <stdio.h>
void swap(int *left, int *right) {
int temporary = *left;
*left = *right;
*right = temporary;
}
int partition(int *values, int low, int high) {
int pivot = values[high];
int boundary = low;
for (int scan = low; scan < high; ++scan) {
if (values[scan] < pivot) {
swap(&values[boundary++], &values[scan]);
}
}
swap(&values[boundary], &values[high]);
return boundary;
}
void quick_sort(int *values, int low, int high) {
if (low >= high) return;
int pivot = partition(values, low, high);
quick_sort(values, low, pivot - 1);
quick_sort(values, pivot + 1, high);
}
int main(void) {
int values[] = {9, 4, 7, 3, 10, 5};
quick_sort(values, 0, 5);
for (int index = 0; index < 6; ++index) {
printf("%d ", values[index]);
}
}
3 4 5 7 9 10
#include <algorithm>
#include <iostream>
#include <vector>
template<class Iterator>
void quick_sort(Iterator first, Iterator last) {
if (last - first < 2) return;
auto pivot = *(last - 1);
auto middle = std::partition(first, last - 1,
[pivot](int value) { return value < pivot; });
std::iter_swap(middle, last - 1);
quick_sort(first, middle);
quick_sort(middle + 1, last);
}
int main() {
std::vector values{9, 4, 7, 3, 10, 5};
quick_sort(values.begin(), values.end());
for (int value : values) {
std::cout << value << ' ';
}
}
3 4 5 7 9 10
C and C++ comparison
partition takes the last value, 5, as the pivot and moves the smaller values 4 and 3 to the front. The pivot is then swapped into position 2, its final place. quick_sort repeats the process on the parts before and after it, giving 3 4 5 7 9 10.
Loops, pointers, lengths, and temporary buffers are written explicitly.
Iterators and standard algorithms separate operations from container representation.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Trace each comparison on paper.
- Test duplicates and extreme values.
- Benchmark the custom implementation against the standard library.
Common mistakes
Including the pivot in a recursive call
Sorting from pivot instead of pivot + 1 can recurse forever.
quick_sort(values, pivot, high);
quick_sort(values, pivot + 1, high);
Missing the base case
Ranges with one or zero elements must return immediately.
int pivot = partition(values, low, high);
if (low >= high) return;
int pivot = partition(values, low, high);
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges