Insertion sort keeps a sorted prefix. For each new element (the key) it shifts larger prefix elements one place right and drops the key into the gap, like sorting playing cards in your hand. It is O(n^2) worst case, O(n) on nearly sorted input, stable, in place, and excellent for small arrays.
Remember
for (i = 1; i < n; i++) {
key = a[i]; j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Insertion Sort in C.
Topic
Detail
Best
O(n) sorted input
Worst
O(n^2) reverse sorted
Stable
Yes
Great for
Small or nearly sorted data
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Merge Sort.
Example 1 — Trace each insertion
Sort 64, 25, 12, 22, 11.
C
#include <stdio.h>
int main(void) {
int a[] = {64, 25, 12, 22, 11};
int n = 5;
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
printf("i=%d:", i);
for (int k = 0; k < n; k++) printf(" %d", a[k]);
printf("\n");
}
return 0;
}