Sorting Algorithms
A sorting algorithm puts a sequence into order. Comparison sorts need at least O(n log n) comparisons in the worst case. In C you write one, or you call qsort.
Detailed Explanation
Pick the algorithm from the constraints.
Insertion sort is O(n^2) writes and O(1) extra space, stable, and fast for n under a few dozen or for nearly sorted data. Production qsort implementations switch to it on small partitions.
Heapsort is O(n log n) worst case, in-place, not stable. It is the guarantee you want when a quicksort adversary would matter.
Mergesort is O(n log n) always, stable, and needs O(n) extra memory for arrays. It is the natural sort for linked lists, where merge does not need a buffer.
Quicksort is O(n log n) average, O(n^2) worst, in-place aside from O(h) stack. A random or median-of-three pivot makes the worst case unlikely. qsort in the C library is often a tuned introsort: quicksort that switches to heapsort when the depth is suspicious.
Counting sort and radix sort beat n log n when the keys are integers in a small range. They are not comparison sorts. They use O(k) or O(n + k) space.
Stability matters when equal keys carry satellite data. qsort is not required to be stable. If you sorted by last name and then want to sort by first name without scrambling last-name groups, you need a stable sort or a single comparator on both fields.
In C, swapping large structs is expensive; sort an array of pointers or of indices. Comparators must not overflow. Floating-point comparators must decide what to do with NaN; an inconsistent NaN order can crash some library sorts.
Test with empty arrays, one element, all equal, already sorted, reverse sorted, and a duplicate-heavy case. Those are the shapes that hide off-by-one and the O(n^2) pivot.
Code Examples
#include <stdio.h>
static void insertion(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];
j--;
}
a[j + 1] = key;
}
}
int main(void)
{
int a[] = { 4, 2, 3, 1 };
insertion(a, 4);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]); /* prints: 1 2 3 4 */
return 0;
}#include <stdio.h>
#include <stdlib.h>
static int cmp(const void *a, const void *b)
{
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void)
{
int a[] = { 4, 2, 3, 1 };
qsort(a, 4, sizeof a[0], cmp);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]); /* prints: 1 2 3 4 */
return 0;
}Common Gotchas
`qsort` is not a stable sort in the standard
do not chain two sorts and expect the first key to break ties.
A comparator that returns `x - y` overflows
use `(x > y) - (x < y)` or explicit branches.
The `O(n log n)` lower bound is for comparison sorts
counting sort is allowed to be linear in `n + k`.
Sorting pointers to strings compares addresses unless the comparator dereferences
see `qsort`.