Insertion sort and Shell sort
Insertion sort takes the next item, shifts every larger one right and drops it into the gap, so nearly sorted data needs only about n comparisons; Shell sort first insertion-sorts items a large gap apart, then shrinks the gap.
A log already sorted by time gets a few late records appended and has to be sorted again. With the last lesson's bubble or selection sort, even 300 records take 44,850 comparisons; but this data is nearly sorted, with only a few records out of place. Insertion sort needs just over 300 comparisons on it. Python's own sorted (Timsort) relies on exactly this: on stretches shorter than 64 it uses insertion sort. This lesson writes insertion sort, counts on three kinds of input why it is so fast when the data is "nearly sorted", then looks at its faster cousin: Shell sort.
Insertion sort: like sorting the cards in your hand
The left part is already sorted. Pick up the next number on the right, key, and look back from just left of it: each number larger than key shifts one place right; at the first one that is not larger, stop, and put key into the gap that opened. The sorted part on the left has grown by one.
Unlike bubble sort, this isn't swap after swap but shifting: a[j + 1] = a[j] writes a single box. key stays in your hand and is put down only at the end.
1key = a[i]2j = i - 13while j >= 0 and a[j] > key:4 a[j + 1] = a[j]5 j -= 16a[j + 1] = key
1def insertion_sort(a):2 a = a[:]3 cmps = moves = 04 for i in range(1, len(a)):5 key = a[i]6 j = i - 17 while j >= 0:8 cmps += 19 if a[j] <= key: # not larger than key: stop10 break11 a[j + 1] = a[j] # shift the larger one right12 moves += 113 j -= 114 a[j + 1] = key15 return a, cmps, moves16 17print(insertion_sort([1, 4, 5, 2, 9]))18print(insertion_sort([5, 1, 4, 9, 2]))19print(insertion_sort([(2, "a"), (1, "b"), (2, "c")]))
([1, 2, 4, 5, 9], 6, 2) ([1, 2, 4, 5, 9], 8, 5) ([(1, 'b'), (2, 'a'), (2, 'c')], 2, 1)
To count comparisons, the while condition is split up; it means the same as the figure's while j >= 0 and a[j] > key. Insertion sort is stable: it stops at an equal item (a[j] <= key), so key never passes it.
Insertion sort 5 2 4 6 1 3. After the first 2 passes (2 and 4 inserted), what does the array look like?
How far can j go? Fill in the blank so the program sorts 5 2 4 6 1 3.
1a = [5, 2, 4, 6, 1, 3]2for i in range(1, len(a)):3 key = a[i]4 j = i - 15 while j >= and a[j] > key:6 a[j + 1] = a[j]7 j -= 18 a[j + 1] = key9print(*a)
a[-1] raises no error, it is the last number, so when j reaches −1 it still gets compared and moved, and the result is a mess.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).
1a = [(2, "A"), (1, "B"), (2, "C"), (1, "D")]2for i in range(1, len(a)):3 key = a[i]4 j = i - 15 while j >= 0 and a[j][0] key[0]:6 a[j + 1] = a[j]7 j -= 18 a[j + 1] = key9print(*[f"{s}{name}" for s, name in a])
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
✓Complete insertion_sort(a): sort in place and return the number of moves (how many times a[j + 1] = a[j] ran).
[1, 2, 4, 5, 9] 2 [1, 2, 3, 4] 0 [1, 2, 3, 4] 6 [1, 1, 2, 3] 4
1def insertion_sort(a):2 moves = 03 # i from 1: key = a[i], shift the larger ones right, then put key down4 return moves5 6for data in [[1, 4, 5, 2, 9], [1, 2, 3, 4], [4, 3, 2, 1], [3, 1, 2, 1]]:7 moves = insertion_sort(data)8 print(data, moves)
Fastest on nearly sorted data
Each move of insertion sort removes exactly one inversion (a pair where the earlier one is larger), so moves = the number of inversions. Comparisons are a little more than moves: each key has one last "not larger, stop".
- Sorted: each key glances left and stops: n − 1 comparisons, 0 moves, O(n).
- Reversed: each key moves all the way to the front: n(n − 1)/2, O(n²).
- Just a few out of place: each one costs a few more.
1def insertion_sort(a):2 a = a[:]3 cmps = moves = 04 for i in range(1, len(a)):5 key = a[i]6 j = i - 17 while j >= 0:8 cmps += 19 if a[j] <= key:10 break11 a[j + 1] = a[j]12 moves += 113 j -= 114 a[j + 1] = key15 return a, cmps, moves16 17n = 30018sorted_in = list(range(n))19few_off = list(range(n))20for k in [10, 80, 150, 220, 290]: # swap 5 pairs of neighbours21 few_off[k], few_off[k + 1] = few_off[k + 1], few_off[k]22mixed = [(i * 7919) % 10007 for i in range(n)]23reversed_in = list(range(n, 0, -1))24 25for name, data in [("sorted", sorted_in), ("5 out of place", few_off), ("mixed", mixed), ("reversed", reversed_in)]:26 _, cmps, moves = insertion_sort(data)27 print(name, "comparisons", cmps, "moves", moves)
sorted comparisons 299 moves 0 5 out of place comparisons 304 moves 5 mixed comparisons 22993 moves 22694 reversed comparisons 44850 moves 44850
Five out of place costs only 5 more comparisons and 5 moves than sorted; mixed and reversed take twenty and forty thousand. Insertion sort's work is proportional to how disordered the data is, while bubble sort (without the early exit) and selection sort make the full n(n − 1)/2 comparisons whatever the input.
That is why Timsort uses it. Real data is often "sorted in stretches": appended logs, reports sorted by day and then joined. Timsort first finds these already sorted stretches (called runs), extends runs that are too short to 32–64 items with insertion sort, then merges the runs in pairs (lesson 3's merging). On short stretches insertion sort has small constants and needs no extra space, so it beats even merging.
Each list has only one number out of place. How many moves does insertion sort make on each?
1def moves(a):2 a = a[:]3 count = 04 for i in range(1, len(a)):5 key = a[i]6 j = i - 17 while j >= 0 and a[j] > key:8 a[j + 1] = a[j]9 count += 110 j -= 111 a[j + 1] = key12 return count13 14print(moves([5, 1, 2, 3, 4]), moves([2, 3, 4, 5, 1]))
[5, 1, 2, 3, 4], 5 is larger than all 4 after it: 4 pairs. In [2, 3, 4, 5, 1], 1 is smaller than all 4 before it: also 4 pairs, and 1 has to move back to the front one place at a time. Only one item is wrong, but it can still be far from where it belongs: insertion sort moves things one place at a time.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?
Shell sort: let far-off items jump first
Insertion sort shares bubble sort's weakness: an item moves only one place at a time. If the smallest is at the end, it takes n − 1 moves. Shell sort (named after its inventor, Donald Shell) first treats items a gap apart as a group and does insertion sort within each group, so a small item far away jumps gap places at once; then it halves the gap and goes again… Finally gap = 1 is plain insertion sort, but by then the list is nearly sorted, exactly when insertion sort is fastest.
1def shell_sort(a):2 a = a[:]3 moves = 04 gap = len(a) // 25 while gap > 0:6 for i in range(gap, len(a)): # insertion sort on items gap apart7 key = a[i]8 j = i - gap9 while j >= 0 and a[j] > key:10 a[j + gap] = a[j]11 moves += 112 j -= gap13 a[j + gap] = key14 gap //= 215 return a, moves16 17def insertion_moves(a):18 a = a[:]19 moves = 020 for i in range(1, len(a)):21 key = a[i]22 j = i - 123 while j >= 0 and a[j] > key:24 a[j + 1] = a[j]25 moves += 126 j -= 127 a[j + 1] = key28 return moves29 30print(shell_sort([9, 8, 7, 3, 2, 1]), insertion_moves([9, 8, 7, 3, 2, 1]))31 32n = 30033for name, data in [("mixed", [(i * 7919) % 10007 for i in range(n)]), ("reversed", list(range(n, 0, -1)))]:34 result, moves = shell_sort(data)35 print(name, "Shell", moves, "insertion", insertion_moves(data), result == sorted(data))
([1, 2, 3, 7, 8, 9], 9) 15 mixed Shell 1434 insertion 22694 True reversed Shell 1000 insertion 44850 True
On 300 reversed numbers insertion sort makes 44,850 moves and Shell sort only 1000. The code just replaces insertion sort's 1 with gap and wraps a loop over gaps around it.
How fast Shell sort is depends on the gaps. The n/2, n/4, …, 1 used here is the simplest and is still O(n²) in the worst case; better sequences (such as 1, 4, 13, 40…, that is gap = 3 × gap + 1) give roughly O(n^1.5). It is not stable: two equal items can fall into different groups and jump separately, losing their order.
| Insertion sort | Shell sort | |
|---|---|---|
| Best | O(n): sorted takes n − 1 comparisons | around O(n log n) |
| Worst | O(n²): reversed | depends on the gaps; O(n²) for the n/2 sequence |
| Work | proportional to the inversions | far-off items jump first, many fewer moves |
| Extra space | O(1) | O(1) |
| Stable | stable | not stable |
| Used in | short stretches, nearly sorted data (inside Timsort) | embedded code with no spare memory |
In interviews: "Which O(n²) sort is most useful?" Insertion sort: close to O(n) when nearly sorted, stable, in place, small constants; Timsort and many C library quicksorts switch to it on short stretches. If asked about Shell sort, say clearly "insertion sort on groups a gap apart, with the gap shrinking to 1", and that it is not stable.
One Shell sort pass with gap = 2 on 5 1 4 2 3. What is the result?
With n = 10, which values does gap = n // 2, while gap > 0, and gap //= 2 after each pass give gap, in order?
Insertion sort and Shell sort: which one is stable?
Groups a gap apart
✓Complete shell_sort(a, gaps): for each gap in gaps (the last is always 1), do an "insertion sort on items gap apart", sorting in place, and return how many moves each gap's pass made.
[3, 6] [1, 2, 3, 7, 8, 9] [8, 5] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [45] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1def shell_sort(a, gaps):2 per_gap = []3 for gap in gaps:4 moves = 05 # like insertion sort, but j steps back gap places and items move to a[j + gap]6 per_gap.append(moves)7 return per_gap8 9a = [9, 8, 7, 3, 2, 1]10print(shell_sort(a, [3, 1]), a)11b = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]12print(shell_sort(b, [4, 1]), b)13c = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]14print(shell_sort(c, [1]), c)
How you write it at work
Sorting a whole list is still sorted / list.sort: it uses insertion sort on short stretches by itself, and nearly sorted input is close to O(n) (1000 sorted numbers take only 999 comparisons).
Where you use the idea of "inserting" yourself is a list kept sorted all the time: each new item goes straight into its place instead of re-sorting every time. bisect.insort finds the place by binary search (O(log n) comparisons), then shifts the rest right (O(n), but as one block in C, so fast):
1import bisect2 3scores = []4for s in [72, 95, 60, 88, 95, 79]:5 bisect.insort(scores, s)6 print(scores)7 8print(bisect.bisect_left(scores, 88), len(scores) - bisect.bisect_right(scores, 80))
[72] [72, 95] [60, 72, 95] [60, 72, 88, 95] [60, 72, 88, 95, 95] [60, 72, 79, 88, 95, 95] 3 3
The last line: 88 is at index 3; 3 scores are above 80.
- Sort once:
sorted/list.sort. - Items arrive one by one and must stay sorted:
bisect.insort, O(n) each, fine up to a few thousand. - Lots of items with frequent inserts and deletes: switch to a heap (if you only need the smallest) or a balanced-tree kind of structure.
- Don't write your own insertion or Shell sort for ordinary lists: the same logic in C's
sortedis dozens of times faster.
A score list that is always kept sorted: each new score is insorted. What does this print?
1from bisect import insort2 3scores = [60, 75, 90]4for s in [88, 60, 100]:5 insort(scores, s)6print(scores, scores.index(88))
Summary
Insertion sort and Shell sort
- Insertion: hold key, shift each larger item one place right, drop key in the gap; stable, in place
- Moves = inversions: sorted is O(n), reversed O(n²), a few out of place cost only a few more
- Timsort uses insertion sort on short runs of 32–64; nearly sorted input is close to O(n)
- Shell: insertion sort on groups a large gap apart first, so far-off items jump over, ending with gap = 1; not stable
- To keep a list sorted: bisect.insort, not re-sorting every time
1while j >= 0 and a[j] > key: # > not >=: stable2 a[j + 1] = a[j]3 j -= 14a[j + 1] = key5bisect.insort(scores, s)