Sorting puts data in order: marks from lowest to highest, names alphabetically, orders by date. In real C programs you will usually call qsort, but writing the classic sorting algorithms yourself teaches loops, swapping, recursion and how to judge an algorithm’s speed. This lesson implements the three simple O(n²) sorts (bubble, selection and insertion) and the two fast O(n log n) sorts (merge sort and quick sort), then tests them on 10,000 numbers.
In this lesson you will learn
- Bubble sort with an early exit
- Selection sort and insertion sort
- Merge sort with a temporary buffer
- Quick sort with the Lomuto partition
- Comparing time complexity and stability
You should know arrays, functions and recursion.
Bubble, Selection and Insertion Sort
#include <stdio.h>
static void print(const char *label, const int *a, int n) {
printf("%-10s", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
static void copy(int *dst, const int *src, int n) {
for (int i = 0; i < n; i++) dst[i] = src[i];
}
/* Bubble sort: swap neighbours that are out of order; stop early if no swaps */
static int bubble_sort(int *a, int n) {
int passes = 0;
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
passes++;
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
swapped = 1;
}
}
if (!swapped) break;
}
return passes;
}
/* Selection sort: put the smallest remaining item at position i */
static void selection_sort(int *a, int n) {
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[min]) min = j;
int t = a[i]; a[i] = a[min]; a[min] = t;
}
}
/* Insertion sort: insert each item into the sorted part on its left */
static void insertion_sort(int *a, int n) {
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; /* shift bigger items right */
j--;
}
a[j + 1] = key;
}
}
int main(void) {
const int data[] = {64, 25, 12, 22, 11, 90, 3};
const int n = sizeof data / sizeof data[0];
int a[7];
print("original", data, n);
copy(a, data, n);
int passes = bubble_sort(a, n);
print("bubble", a, n);
printf("bubble needed %d passes\n", passes);
copy(a, data, n);
selection_sort(a, n);
print("selection", a, n);
copy(a, data, n);
insertion_sort(a, n);
print("insertion", a, n);
int sorted[] = {1, 2, 3, 4, 5, 6, 7};
printf("bubble on sorted input: %d pass\n", bubble_sort(sorted, 7));
return 0;
}
Output
original 64 25 12 22 11 90 3
bubble 3 11 12 22 25 64 90
bubble needed 6 passes
selection 3 11 12 22 25 64 90
insertion 3 11 12 22 25 64 90
bubble on sorted input: 1 pass
- Bubble sort compares neighbours and swaps them when they are out of order. After each pass the largest remaining value has “bubbled” to the end, so the inner loop can stop one place earlier. If a whole pass makes no swaps the array is sorted, which is why an already-sorted array needed just 1 pass.
- Selection sort finds the smallest remaining value and swaps it into position
i. It always does about n²/2 comparisons but at most n − 1 swaps, which helps when writing to memory is expensive. - Insertion sort takes each value and shifts larger values in the sorted part one place right until the gap is in the right spot, like sorting playing cards in your hand. It is very fast on data that is already almost sorted.
- Each test copies the original data first, so every algorithm sorts the same input.
Merge Sort and Quick Sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Merge sort: split in half, sort each half, merge the two sorted halves */
static void merge(int *a, int *tmp, int lo, int mid, int hi) {
int i = lo, j = mid, k = lo;
while (i < mid && j < hi)
tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++]; /* <= keeps it stable */
while (i < mid) tmp[k++] = a[i++];
while (j < hi) tmp[k++] = a[j++];
memcpy(a + lo, tmp + lo, (size_t)(hi - lo) * sizeof *a);
}
static void merge_sort_rec(int *a, int *tmp, int lo, int hi) { /* sorts a[lo..hi-1] */
if (hi - lo < 2) return;
int mid = lo + (hi - lo) / 2;
merge_sort_rec(a, tmp, lo, mid);
merge_sort_rec(a, tmp, mid, hi);
merge(a, tmp, lo, mid, hi);
}
static void merge_sort(int *a, int n) {
int *tmp = malloc((size_t)n * sizeof *tmp);
if (tmp == NULL) return;
merge_sort_rec(a, tmp, 0, n);
free(tmp);
}
/* Quick sort (Lomuto partition): put the pivot in its final place, recurse on both sides */
static void quick_sort(int *a, int lo, int hi) { /* sorts a[lo..hi] */
if (lo >= hi) return;
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; j++) {
if (a[j] < pivot) {
int t = a[i]; a[i] = a[j]; a[j] = t;
i++;
}
}
int t = a[i]; a[i] = a[hi]; a[hi] = t;
quick_sort(a, lo, i - 1);
quick_sort(a, i + 1, hi);
}
static int is_sorted(const int *a, int n) {
for (int i = 1; i < n; i++)
if (a[i - 1] > a[i]) return 0;
return 1;
}
int main(void) {
int a[] = {38, 27, 43, 3, 9, 82, 10};
int b[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof a / sizeof a[0];
merge_sort(a, n);
quick_sort(b, 0, n - 1);
for (int i = 0; i < n; i++) printf("%d%s", a[i], i < n - 1 ? " " : "\n");
for (int i = 0; i < n; i++) printf("%d%s", b[i], i < n - 1 ? " " : "\n");
/* Test on 10,000 pseudo-random numbers (fixed seed, so repeatable) */
enum { N = 10000 };
static int big1[N], big2[N];
srand(42);
for (int i = 0; i < N; i++) big1[i] = big2[i] = rand() % 100000;
merge_sort(big1, N);
quick_sort(big2, 0, N - 1);
printf("merge sorted: %s, quick sorted: %s, same result: %s\n",
is_sorted(big1, N) ? "yes" : "no", is_sorted(big2, N) ? "yes" : "no",
memcmp(big1, big2, sizeof big1) == 0 ? "yes" : "no");
return 0;
}
Output
3 9 10 27 38 43 82
3 9 10 27 38 43 82
merge sorted: yes, quick sorted: yes, same result: yes
- Merge sort splits the array in half, sorts each half recursively, then merges the two sorted halves by repeatedly taking the smaller front item. It always runs in O(n log n) time but needs a temporary array of the same size.
- Using
<=in the merge keeps equal values in their original order, which makes merge sort stable. - Quick sort picks a pivot (here the last element), moves smaller values to its left, places the pivot in its final position, then sorts each side. It sorts in place and is usually the fastest in practice.
- Quick sort’s worst case is O(n²), when the pivot is always the smallest or largest value, for example on already-sorted data with this simple pivot choice. Real implementations pick a random or median pivot to avoid it.
- The large test fills two arrays with the same 10,000 pseudo-random numbers (a fixed seed makes the run repeatable), sorts one with each algorithm, and checks that both results are sorted and identical.
Comparing the Algorithms
| Algorithm | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) stack | No |
A stable sort keeps items with equal keys in their original order. That matters when you sort records by one field after sorting them by another.
Common Mistakes
- Off-by-one loop limits, such as comparing
a[j]witha[j + 1]whenjcan reachn - 1, which reads past the array. - Computing
(lo + hi) / 2for very large indexes, which can overflow. Uselo + (hi - lo) / 2. - Using an O(n²) sort on large data. Sorting a million items with bubble sort takes about a trillion comparisons.
- Forgetting to free the merge sort buffer.
Practice Exercises
Exercise 1. Change insertion sort to sort in descending order.
Show answer
Change the comparison in the inner loop from a[j] > key to a[j] < key. Smaller values are then shifted right, so the largest values end up first.
Exercise 2. Count how many swaps bubble sort makes on {5, 1, 4, 2, 8}.
Show answer
4 swaps: (5,1), (5,4), (5,2) in the first pass and (4,2) in the second. The number of swaps always equals the number of pairs that are out of order, called inversions.
Frequently Asked Questions
Which sorting algorithm should I use in real programs?
Use the library: qsort in C. Write your own only for learning, for special needs such as a stable sort or sorting a linked list, or when an interview asks for it.
Why is insertion sort used inside fast sorting libraries?
For very small arrays, about 10 to 20 items, its low overhead beats the recursive algorithms. Many library sorts switch to insertion sort once a part of the array becomes that small.
Summary
- Bubble, selection and insertion sort are simple but O(n²).
- Merge sort is always O(n log n) and stable but needs extra memory.
- Quick sort is fast in place on average, but has an O(n²) worst case.
- In production code, call
qsort.
Next: Binary Search in C.
