Insertion sort is a simple sorting algorithm that takes the values one at a time, shifts the larger values of the sorted part one place right and drops each value into the gap, so the sorted part grows from the left. It takes O(n) time on sorted input and O(n²) on average and in the worst case. It needs O(1) extra space and is stable. This page explains how it works, with step-by-step animations of the first insertions, the remaining insertions and an already sorted array from the VisiGrab app.
// how insertion sort works
Insertion sort, also called straight insertion sort, is a simple sorting algorithm that builds a sorted part at the left end of an array. Each pass takes the next value, shifts the larger values of the sorted part one place right and drops the value into the gap, the way many people sort a hand of cards. It takes O(n) time in the best case, O(n2) on average and in the worst case, and O(1) extra space. It is stable.
Positions count from 0, as in the app. Position 0 alone starts as the sorted part. Pass i stores the value at position i aside: the app's code calls it temp, and textbooks often call it the key. It is compared with the sorted values from right to left. Each larger one shifts one place right, and the stored value goes into the gap that is left. n values always take n − 1 passes; only the work per pass varies.
In pseudocode:
for i from 1 to n - 1
temp = a[i]
j = i
while j > 0 and a[j - 1] > temp
a[j] = a[j - 1]
j = j - 1
a[j] = temp
The outer loop runs i from 1 to n − 1 and sets temp = a[i] and j = i. The inner loop runs while j > 0 and a[j - 1] > temp: it copies a[j - 1] into a[j] and decreases j. Then a[j] = temp.
The usual version shifts instead of swapping. A swap version makes the same moves, but at three writes each, where a shift is one. The sorted part is sorted but not final, since a later, smaller value can still be inserted inside it. In selection sort it is final.
The player runs the first two passes on the app's default array, 5, 2, 1, 4, 0, 6, 3. Each pass lowers the next value out of its cell, shifts the larger sorted values right and lets it rise into the gap: three comparisons and three shifts leave 1, 2, 5, 4, 0, 6, 3.
The bracket hides while a value is lowered and comes back one cell wider.
The player runs passes 3 to 6 from 1, 2, 5, 4, 0, 6, 3: 11 comparisons and eight shifts leave 0, 1, 2, 3, 4, 5, 6. In pass 5, 6 is already in place, so nothing is lowered.
The figure shows the array after every pass.
An adaptive sort does less work on input that is already in order. On the sorted array 0, 1, 2, 3, 4, 5, 6, each pass compares the next value with the last sorted one only. That one is never larger, so nothing is lowered or shifted.
That is n − 1 = 6 comparisons and no shifts: the best case, O(n). Bubble sort needs a flag for this, and selection sort still makes 21 comparisons. Nearly sorted input is fast too: the cost is O(n + d) for d pairs of values in the wrong order, or O(nk) when no value is more than k places from its final position.
Yes. It shifts only values strictly larger than the stored one, so a value never passes an equal one; the example below shows it.
Usually. On random arrays it makes about half as many comparisons, and on sorted ones only n − 1. Selection sort wins only where writes are expensive, as the comparison below explains.
Each shift moves one larger value past the stored one, so it removes one inversion, a pair of values in the wrong order: shifts equal inversions. The default array has 11: inserting 2 takes one shift, 1 two, 4 one, 0 four, 6 none and 3 three. Each pass also makes one comparison that finds a value not larger, unless the stored value reaches position 0. So the default array's 14 comparisons are 11 shifts + 6 passes − 3 passes that end at position 0: those that insert 2, 1 and 0.
| Case | Comparisons | Shifts | Time | Extra space |
|---|---|---|---|---|
| Best: already sorted | n − 1 | 0 | O(n) | O(1) |
| Average: random order | About n2/4 | n(n − 1)/4 on average | O(n2) | O(1) |
| Worst: reverse sorted | n(n − 1)/2 | n(n − 1)/2 | O(n2) | O(1) |
Reverse order costs the most: 21 comparisons and 21 shifts on 6, 5, 4, 3, 2, 1, 0. The only extra memory is the stored value, so insertion sort is in-place.
A stable sort keeps equal values in their original order. Insertion sort shifts only values strictly larger than the stored one, so a value stops at the first element that is not larger and never passes an equal one. In 2a, 2b, 1, pass 1 finds 2a not larger than 2b, so nothing moves. Pass 2 shifts both 2s one cell right, in order, and 1 goes to the front: 1, 2a, 2b.
Selection sort turns the same three values into 1, 2b, 2a. Shifting values that are larger than or equal to the stored one would still sort, but would not be stable.
On the default array insertion sort makes 14 comparisons and 11 shifts. Bubble sort with its early exit makes 20 comparisons and 11 swaps, also one per inversion, but at three writes each. Selection sort makes 21 comparisons and five swaps. So insertion sort is usually the fastest of the three, and selection sort wins only where writes are expensive. Merge sort, heap sort and quick sort suit large arrays: they take O(n log n) time, quick sort on average.
O(n log n) in all. The shifts stay O(n2). To stay stable, it must search for the place after the last equal value.O(n2), plus O(n) stack. Insertion sort is incremental, not divide and conquer.O(n2), and no binary search.The app shows the code in all three, linked to the full source on GitHub. The listings make the same comparisons and shifts and sort the caller's array in place. Each pass writes temp back even when nothing shifted: a harmless self-write that the app's animation skips.
Note
The C++ function takes std::vector<int>&, a reference, so it sorts the caller's vector, not a copy.
Note
Python's bisect.insort inserts one value into a sorted list: a binary search, then list.insert, which shifts the tail, so each call is O(n). It inserts after equal values, so they keep their order of arrival.
The full source code is on GitHub, in Python, Java and C++.
Insertion sort suits small arrays and nearly sorted data. It is also online: each pass needs only the sorted part, so values can be sorted as they arrive. Library sorts use it for small parts:
list.sort() and sorted() use binary insertion sort for lists of fewer than 64 items and for short runs in longer ones.Arrays.sort on an int, long, float or double array insertion-sorts the leftmost part below 44 values. Other small parts get a mixed insertion sort, below a limit that starts at 72 and grows with the recursion depth. For objects, TimSort uses binary insertion sort below 32 elements and for short runs in longer arrays.std::sort is an introsort. GCC's libstdc++ stops at ranges of 16 or fewer and finishes with one insertion sort pass over the whole array. LLVM's libc++ insertion-sorts each range of 6 to 23 values and sorts shorter ones with fixed comparison sequences.// in the app
In VisiGrab insertion sort runs on the default, a random or your own array of seven values, with a step for every lowered value, shift and insertion: 43 steps on the default array.
Custom opens a seven-cell dialog for values from 0 to 99, equal ones included, with buttons for an ascending or a descending fill. Random picks seven distinct values from 0 to 19.
Step forward and back through all 43 steps on the default array, each with its message and an animation in both directions. Restart replays the array, and the last array you used comes back next time.
A single page: the sorted and unsorted sections, in-place with O(1) auxiliary space, stable and adaptive, O(n) on already or almost sorted arrays, O(n²) on average and in the worst case, and why simple sorts still pay off on small data.
The insertionSort method in Java and the insertion_sort function in Python and C++, each explained as picking up the next value as temp and shifting larger elements right until it fits. Links lead to the full source on GitHub.
Eight questions with an explanation for every answer, from shifting instead of swapping to why the sorted prefix is not final yet.
Bubble sort, selection sort, merge sort, heap sort and quick sort each have a topic of their own.
// build your own
Download VisiGrab and step through every shift and insertion, on the default array, on a sorted one or on an array of your own.
Insertion sort is one of 30+ topics. See them all