Insertion sort
Insert each element into its correct place in the already-sorted left part.
Syllabus says: “Insertion Sort”
On this page · 19 sections
Take the next card, SHIFT bigger ones right, DROP it into the gap. Already sorted → O(n).
Arranging playing cards in your hand: pick up one card at a time and slide it into its correct place.
Insertion sort builds a sorted prefix by taking the next element and inserting it into its correct position among the elements before it, shifting larger elements one place right.
Learning objectives
- Trace insertion sort using a key and shifting.
- Derive best, average and worst case complexities (a KTU favourite — May 2026 Q10b).
- Explain why insertion sort is stable and adaptive.
Prerequisites
Arrays, while loops, the idea of a loop invariant.
Introduction
It is how most people sort playing cards in their hand: pick up the next card and slide it left past every larger card until it fits.
Definition
Insertion sort maintains the invariant that a[0..i−1] is sorted. In pass i it removes key = a[i], shifts every element of the sorted part that is greater than key one place right, and writes key into the gap.
How it works
- key ← a[i]; j ← i − 1.
- While j ≥ 0 and a[j] > key: a[j+1] ← a[j]; j ← j − 1 (shift, not swap).
- a[j+1] ← key.
- Repeat for i = 1 … n−1.
Using strict a[j] > key (not ≥) is what keeps equal elements in their original order — this makes the sort stable.
Where it is used
Excellent for small or nearly sorted arrays. Library sorts (e.g. hybrid quick/merge sorts) switch to insertion sort for sub-arrays of roughly 16 elements or fewer.
Worked example
| Input | 5 2 4 6 1 3 |
|---|---|
| After pass 1 | 2 5 4 6 1 3 |
| After pass 2 | 2 4 5 6 1 3 |
| After pass 3 | 2 4 5 6 1 3 |
| After pass 4 | 1 2 4 5 6 3 |
| After pass 5 | 1 2 3 4 5 6 |
Totals: comparisons = 12, shifts = 9
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1InsertionSort(a, n)
- 2for i ← 1 to n − 1
- 3key ← a[i]; j ← i − 1
- 4while j ≥ 0 and a[j] > key
- 5a[j + 1] ← a[j]; j ← j − 1
- 6a[j + 1] ← key
- 7end
C implementation
insertion_sort.ctested ✓ 132/132 cases/* Insertion sort — KTU PCCST303, Module 4
* Input : n followed by n integers
* Output: the array after every pass, then the sorted array. */
#include <stdio.h>
#define MAX 100
void printArray(const char *label, int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void insertionSort(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) { /* shift larger elements right */
a[j + 1] = a[j];
j--;
}
a[j + 1] = key; /* drop key into the gap */
printArray("PASS", a, n);
}
}
int main(void) {
int n, a[MAX];
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
insertionSort(a, n);
printArray("SORTED", a, n);
return 0;
}
Sample run · KTU PYQ input · real output from gcc
Input (stdin)
7 34 21 3 121 342 65 44
Output (stdout)
PASS: 21 34 3 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 121 342 65 44 PASS: 3 21 34 65 121 342 44 PASS: 3 21 34 44 65 121 342 SORTED: 3 21 34 44 65 121 342
Complexity
| Case | Input | Comparisons | Time |
|---|---|---|---|
| Best | already sorted | n − 1 | O(n) |
| Average | random | ≈ n²/4 | O(n²) |
| Worst | reverse sorted | n(n − 1)/2 | O(n²) |
The simulator counts comparisons for you — try a sorted input and then the same values reversed.
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Stable, in-place, online (can sort as data arrives) | O(n²) on large random inputs |
| Adaptive: O(n + number of inversions) | Many shifts when the input is reversed |
Edge cases
- j reaches −1 when the key is the smallest so far — the j ≥ 0 test must come first to avoid reading a[−1].
- Duplicates keep their relative order.
- n ≤ 1: nothing to do.
Common mistakes
- Writing a[j] > key before j ≥ 0 in C — reads out of bounds when j = −1.
- Swapping at each step instead of shifting (works, but triples the writes).
- Forgetting the final a[j+1] = key.
Asked in KTU exams (2)
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Invariant: a[0..i−1] sorted.
- Best O(n), average/worst O(n²); space O(1).
- Stable, in-place, adaptive, online.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing)
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 §2.1–2.2
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)