Insertion Sort, step by step.

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

What is insertion sort?

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.

Insertion sort algorithm: shifts and pseudocode

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.

Insertion sort example: the first insertions

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 first two insertions

All steps as text
  1. Sort the array using the Insertion Sort algorithm.
  2. Compare the first two elements. If they're in the correct order, take no action.
  3. If elements are in the incorrect order, temporarily store the smaller element’s value.
  4. Shift the larger element one position to the right to make space.
  5. Check if the stored value fits in the newly created space.
  6. Place the stored smaller value into the first position.
  7. With two elements sorted, continue sorting the rest of the array.
  8. Compare the next unsorted element with the last element in the sorted section.
  9. If elements are in the incorrect order, temporarily store the smaller element’s value.
  10. Shift the larger element one position to the right to make space.
  11. Check if the stored value fits in the newly created space.
  12. Shift the larger element one position to the right to make space.
  13. Check if the stored value fits in the newly created space.
  14. Place the stored smaller value into the first position.
  15. Continue until the whole array is sorted.
  16. Passes 1 and 2 made three comparisons and three shifts. 1, 2 and 5 are sorted, but none of them is in its final place yet.
Insertion Sort — The first two insertions. Last step: Passes 1 and 2 made three comparisons and three shifts. 1, 2 and 5 are sorted, but none of them is in its final place yet.

The bracket hides while a value is lowered and comes back one cell wider.

Insertion sort example: the remaining insertions

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 remaining insertions

All steps as text
  1. The first two passes have sorted 1, 2 and 5. Each new pass compares the next value with the sorted section, starting at its right end.
  2. Compare the next unsorted element with the last element in the sorted section.
  3. If elements are in the incorrect order, temporarily store the smaller element’s value.
  4. Shift the larger element one position to the right to make space.
  5. Check if the stored value fits in the newly created space.
  6. If no larger elements exist to the left, insert the stored value into the open space.
  7. Continue until the whole array is sorted.
  8. Compare the next unsorted element with the last element in the sorted section.
  9. If elements are in the incorrect order, temporarily store the smaller element’s value.
  10. Shift the larger element one position to the right to make space.
  11. Check if the stored value fits in the newly created space.
  12. Shift the larger element one position to the right to make space.
  13. Check if the stored value fits in the newly created space.
  14. Shift the larger element one position to the right to make space.
  15. Check if the stored value fits in the newly created space.
  16. Shift the larger element one position to the right to make space.
  17. Check if the stored value fits in the newly created space.
  18. Place the stored smaller value into the first position.
  19. Continue until the whole array is sorted.
  20. Compare the next unsorted element with the last element in the sorted section.
  21. If elements are already in order, extend the sorted section without shifts.
  22. Compare the next unsorted element with the last element in the sorted section.
  23. If elements are in the incorrect order, temporarily store the smaller element’s value.
  24. Shift the larger element one position to the right to make space.
  25. Check if the stored value fits in the newly created space.
  26. Shift the larger element one position to the right to make space.
  27. Check if the stored value fits in the newly created space.
  28. Shift the larger element one position to the right to make space.
  29. Check if the stored value fits in the newly created space.
  30. Insert the stored value into the space, as it is larger than all elements to its left. The array is now fully sorted.
  31. Passes 3 to 6 made 11 comparisons and eight shifts. The whole sort took 14 comparisons and 11 shifts, one for each pair of values that started out of order.
Insertion Sort — The remaining insertions. Last step: The array is sorted: 0, 1, 2, 3, 4, 5, 6.

The figure shows the array after every pass.

Seven rows of seven cells, labeled Start and Pass 1 to Pass 6. Start is the unsorted array 5, 2, 1, 4, 0, 6, 3; after pass 1 it is 2, 5, 1, 4, 0, 6, 3; after pass 2, 1, 2, 5, 4, 0, 6, 3; after pass 3, 1, 2, 4, 5, 0, 6, 3; after pass 4, 0, 1, 2, 4, 5, 6, 3; after pass 5 it is unchanged; after pass 6, 0, 1, 2, 3, 4, 5, 6. Under each pass row a bracket covers the sorted cells at the left end, labeled Sorted in the first: two cells after pass 1, three after pass 2, and so on, and all seven after pass 6.
Pass k inserts the value at position k into the sorted part and widens the Sorted bracket to cells 0 to k. Sorted values still move when a smaller value arrives, and pass 5 finds 6 already in place.

Insertion sort is adaptive: the best case on a sorted array

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.

An already sorted array

All steps as text
  1. Sort the array using the Insertion Sort algorithm.
  2. Compare the first two elements. If they're in the correct order, take no action.
  3. Include the first two elements in the sorted section. Continue the process for the remainder of the array.
  4. Compare the next unsorted element with the last element in the sorted section.
  5. If elements are already in order, extend the sorted section without shifts.
  6. Compare the next unsorted element with the last element in the sorted section.
  7. If elements are already in order, extend the sorted section without shifts.
  8. Compare the next unsorted element with the last element in the sorted section.
  9. If elements are already in order, extend the sorted section without shifts.
  10. Compare the next unsorted element with the last element in the sorted section.
  11. If elements are already in order, extend the sorted section without shifts.
  12. Compare the next unsorted element with the last element in the sorted section.
  13. The array is fully sorted.
  14. Six comparisons and no shifts for seven sorted values. Insertion sort is adaptive: this is its best case, O(n).
Insertion Sort — An already sorted array. Last step: The array 0, 1, 2, 3, 4, 5, 6 is unchanged: no value had to shift.

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.

Is insertion sort stable?

Yes. It shifts only values strictly larger than the stored one, so a value never passes an equal one; the example below shows it.

Is insertion sort faster than selection sort?

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.

Insertion sort time complexity: comparisons and shifts

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.

CaseComparisonsShiftsTimeExtra space
Best: already sortedn − 10O(n)O(1)
Average: random orderAbout n2/4n(n − 1)/4 on averageO(n2)O(1)
Worst: reverse sortedn(n − 1)/2n(n − 1)/2O(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.

Why insertion sort is stable

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.

Three rows of three cells, labeled Start, Pass 1 and Pass 2. Start holds a 2 marked a, a 2 marked b, and 1. After pass 1 the row is unchanged, with a Sorted bracket under the first two cells. After pass 2 the row is 1, the 2 marked a, the 2 marked b, with the bracket under all three cells: both 2s moved one cell right and kept their order.
Pass 1 shifts nothing, since the first 2 is not larger than the second; pass 2 shifts both 2s right, in order, and puts 1 at the front, so the equal values keep their original order.

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.

Insertion sort vs selection sort vs bubble sort

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.

Binary insertion sort and other variants

  • Binary insertion sort finds the place by binary search: about log2 i comparisons in pass i, 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.
  • Shell sort runs insertion sort over values a gap apart, with gaps that shrink to 1, so values move far in one step. It is not stable.
  • For descending order, shift the values that are smaller than the stored one.
  • A recursive version follows T(n) = T(n − 1) + O(n): still O(n2), plus O(n) stack. Insertion sort is incremental, not divide and conquer.
  • On a linked list, relinking a node replaces the shifts, but finding the place is still a walk along the list: O(n2), and no binary search.

Insertion sort in Python, Java and C++

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++.

When insertion sort is used

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:

  • Python's list.sort() and sorted() use binary insertion sort for lists of fewer than 64 items and for short runs in longer ones.
  • Since Java 14, 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.
  • C++'s 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.

Three animations here.
The whole topic 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.

Your own 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.

Forward and back

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.

Theory and complexity

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.

Python, Java and C++

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.

Quiz

Eight questions with an explanation for every answer, from shifting instead of swapping to why the sorted prefix is not final yet.

Five more sorts

Bubble sort, selection sort, merge sort, heap sort and quick sort each have a topic of their own.

Sort an array
shift by shift.

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