Insertion sort and Shell sort
Insertion sort keeps the front sorted and slides each new element back into place, like sorting a hand of cards: O(n) on nearly sorted data, O(n²) at worst, and stable; Shell sort runs it over elements a gap apart, halving the gap down to 1.
Sorting a hand of cards, you don't swap pairs the way bubble sort does: the cards in your left hand are in order, you pick up a new one, and you slide it back to where it belongs. That is insertion sort.
Insertion sort: the front is sorted, insert the next one
a[0] on its own is sorted. From a[1] on, take key = a[i] out; everything before it that is bigger moves back one place, and key goes into the gap.
1int key = a[i], j = i - 1;2while (j >= 0 && a[j] > key) {3 a[j + 1] = a[j];4 j--;5}6a[j + 1] = key;
Insertion sort 5 2 4 6 1 3. After the first 2 passes (2 and 4 inserted), what does the array look like?
In C: shift, don't swap
In C, the outer loop runs i from 1 to n − 1, and each pass inserts a[i] into the already sorted a[0..i−1].
The code doesn't swap, it shifts: key is taken out first, the bigger ones are copied back one at a time, and key is written just once. Half the assignments of swapping every time.
1#include <stdio.h>2 3int main(void) {4 int a[] = {5, 2, 4, 6, 1, 3};5 int n = 6;6 for (int i = 1; i < n; i++) {7 int key = a[i];8 int j = i - 1;9 while (j >= 0 && a[j] > key) {10 a[j + 1] = a[j];11 j--;12 }13 a[j + 1] = key;14 }15 for (int i = 0; i < n; i++)16 printf("%d ", a[i]);17 printf("\n");18 return 0;19}
1 2 3 4 5 6
Equal numbers don't move (the test is a[j] > key, not >=), so key stops right behind a number equal to it. That makes insertion sort stable.
How far can j go? Fill in the blank so the program sorts 5 2 4 6 1 3.
1#include <stdio.h>2 3int main(void) {4 int a[] = {5, 2, 4, 6, 1, 3};5 int n = 6;6 for (int i = 1; i < n; i++) {7 int key = a[i];8 int j = i - 1;9 while (j >= && a[j] > key) {10 a[j + 1] = a[j];11 j--;12 }13 a[j + 1] = key;14 }15 for (int i = 0; i < n; i++)16 printf("%d ", a[i]);17 printf("\n");18 return 0;19}
Each person has a score and a name, insertion-sorted by score from low to high. The test as written moves people with the same score back too. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).
1#include <stdio.h>2 3typedef struct {4 int score;5 char name;6} Item;7 8int main(void) {9 Item a[] = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};10 int n = 4;11 for (int i = 1; i < n; i++) {12 Item key = a[i];13 int j = i - 1;14 while (j >= 0 && a[j].score key.score) {15 a[j + 1] = a[j];16 j--;17 }18 a[j + 1] = key;19 }20 for (int i = 0; i < n; i++)21 printf("%d%c ", a[i].score, a[i].name);22 printf("\n");23 return 0;24}
1B 1D 2A 2C
>= also moves back someone whose score equals key's, so key lands in front of them and the order flips. With >, it stops on a tie, and insertion sort is stable.Write insertion sort
✓Finish insertion sort: take key out, shift the bigger ones back, put key in.
1 2 3 6 7 8
1#include <stdio.h>2 3int main(void) {4 int a[] = {8, 3, 6, 1, 7, 2};5 int n = 6;6 for (int i = 1; i < n; i++) {7 int key = a[i];8 int j = i - 1;9 // shift the ones bigger than key back one place, j moving forward; then a[j + 1] = key10 }11 for (int i = 0; i < n; i++)12 printf("%d ", a[i]);13 printf("\n");14 return 0;15}
Fast when it's nearly sorted
How many shifts a pass makes depends on how many before key are bigger. On a sorted array nothing shifts and each pass compares once, n − 1 in all: O(n). On a reversed array each one goes to the very front: O(n²).
Of 8 numbers only 6 and 5 are out of order. How many shifts does insertion sort make?
1#include <stdio.h>2 3int main(void) {4 int a[] = {1, 2, 3, 4, 6, 5, 7, 8};5 int n = 8, moves = 0;6 for (int i = 1; i < n; i++) {7 int key = a[i], j = i - 1;8 while (j >= 0 && a[j] > key) {9 a[j + 1] = a[j];10 j--;11 moves++;12 }13 a[j + 1] = key;14 }15 printf("%d\n", moves);16 return 0;17}
std::sort and Python's sort both use insertion sort on short or nearly sorted runs.Insertion sort on n numbers that are already sorted: how many comparisons in total?
Insertion sort on 2 1 4 3 6 5: how many moves in total?
Count the inversions
✓Use insertion sort to count the inversions (pairs where the earlier one is bigger): one per shift.
8
1#include <stdio.h>2 3int main(void) {4 int a[] = {3, 1, 4, 1, 5, 9, 2, 6};5 int n = 8, inv = 0;6 // insertion sort, inv++ on every shift7 printf("%d\n", inv);8 return 0;9}
Shell sort: compare far apart, then closer
Insertion sort is slow when a small number sits at the end: it moves forward one place at a time. Shell sort first groups by a gap (indexes gap apart are one group) and insertion-sorts each group, so a small number jumps gap places at once; then the gap halves, and at gap = 1 it's plain insertion sort, on an array that is by now nearly sorted.
One Shell sort pass with gap = 2 on 5 1 4 2 3. What is the result?
Shell sort in C
Shell sort's code is almost the same as insertion sort's. This program sorts 10 numbers in reverse order and prints the array after each pass, so you can see it get closer to sorted pass by pass:
1#include <stdio.h>2 3int main(void) {4 int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};5 int n = 10;6 for (int gap = n / 2; gap > 0; gap /= 2) {7 for (int i = gap; i < n; i++) {8 int key = a[i], j = i - gap;9 while (j >= 0 && a[j] > key) {10 a[j + gap] = a[j];11 j -= gap;12 }13 a[j + gap] = key;14 }15 printf("gap = %d: ", gap);16 for (int i = 0; i < n; i++)17 printf("%d ", a[i]);18 printf("\n");19 }20 return 0;21}
gap = 5: 4 3 2 1 0 9 8 7 6 5 gap = 2: 0 1 2 3 4 5 6 7 8 9 gap = 1: 0 1 2 3 4 5 6 7 8 9
Change every 1 in insertion sort to gap, wrap a loop around it taking the gap from n/2 down to 1 by halves, and you have Shell sort. Its complexity depends on the gaps; with the usual ones it's around O(n^1.3). It isn't stable (equal values can be in different groups and get swapped apart).
In exams: given an array and a gap sequence (say 5, 3, 1), write the array after each pass. The way: circle the numbers gap apart as one group, sort each group on its own, and write them back in their places.
With n = 10, which values does for (int gap = n / 2; gap > 0; gap /= 2) give gap, in order?
Insertion sort and Shell sort: which one is stable?
Summary
Insertion sort: pick one up, slide it back into place
- The front is sorted; bigger ones shift back, key is written once
- O(n) when sorted, O(n²) reversed; shifts = inversions; stable
- Shell: insertion sort by gap groups, the gap halving down to 1; not stable
1key = a[i]; j = i - 1;2while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }3a[j + 1] = key;