Sorting arranges items in order so that searching, merging, and grouping become faster. Simple sorts (bubble, selection, insertion) are easy to write and run in O(n^2). Divide-and-conquer and heap-based sorts (merge, quick, heap) run in O(n log n). Non-comparison sorts (counting, bucket, radix) can reach linear time for restricted keys. This section walks through each algorithm with a traced example and ends with a comparison.
Trace small arrays by hand.
Print the array after each pass. Watching five numbers move teaches a sort faster than reading code.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (12 tutorials).
A quick taste of sorting. Compile with gcc file.c -std=c11 -Wall -o out.
Example 1 — Sort three numbers with swaps
Compare and swap until ordered.
C
#include <stdio.h>
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
int main(void) {
int a = 3, b = 1, c = 2;
if (a > b) swap(&a, &b);
if (b > c) swap(&b, &c);
if (a > b) swap(&a, &b);
printf("%d %d %d\n", a, b, c);
return 0;
}
Output
1 2 3
How It Works
The first swap gives 1, 3, 2.
The second swap gives 1, 2, 3.
The third comparison finds nothing to do. Every sort is built from compare-and-swap steps like these.
Index
C Sorting Algorithms Topics
Every guide in this section with a one-line summary (12 tutorials).