C/C++ Algorithms

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.

  • Intermediate
  • 6 min read
  • 2 runnable examples
What you'll learn
  • Choosing a pivot and partitioning
  • Recursing on the two sides
  • Average O(n log n) versus worst-case O(n²)
Partition around pivot 7
3< 7
5< 7
4< 7
7pivot
10> 7
9> 7
7 is now in place; quick sort repeats on 3 5 4 and on 10 9.

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.

From lining up by height to code
pivot = values[high]🧍 Choose one person as the reference
values[scan] < pivot↔️ Shorter people move to the left
swap(&values[boundary], &values[high])📍 The pivot steps into its final place
quick_sort(...) on both sides🔁 Each side repeats with its own pivot
Partition around a pivot, then sort each side.
In one sentence

Quick 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

  1. partition uses the last value as pivot and moves smaller values in front of boundary.
  2. The final swap puts the pivot at boundary, its correct sorted position.
  3. quick_sort then sorts the parts before and after the pivot; no merge step is needed.
  4. The C++ version uses std::partition with a lambda for the same step.

When to use it

  • Fast in-place sorting of arrays.
  • Understanding how library sorts such as std::sort work.
  • 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 or std::stable_sort.

Quick Sort visualizer

Use Play or Step to follow each comparison and data movement.

C and C++ code examples

C
Run code →
main.c
#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]);
    }
}
Get a Run button for this example Result of running the code
3 4 5 7 9 10
C++
Run code →
main.cpp
#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 << ' ';
    }
}
Get a Run button for this example Result of running the code
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.

C

Loops, pointers, lengths, and temporary buffers are written explicitly.

C++

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.

Problem
quick_sort(values, pivot, high);
Fix
quick_sort(values, pivot + 1, high);

Missing the base case

Ranges with one or zero elements must return immediately.

Problem
int pivot = partition(values, low, high);
Fix
if (low >= high) return;
int pivot = partition(values, low, high);

Finished this lesson?

Mark it as learned to track your progress.

Next: Merge Sort →

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