Skip to content

Insertion Sort ​

Insertion sort is a sort that takes out values one at a time and slots each one into the right place in the already sorted front part.

At a Glance ​

  • It is similar to how you sort the cards in your hand. When you receive a new card, you find where it belongs among the cards already arranged and slot it in.
  • It is similar to selection sort, but a somewhat more efficient sorting algorithm.
  • Starting from the 2nd element, it compares with the elements in front of it (to the left) to decide where to insert, shifts those elements back one position, and inserts the value in that spot.
  • In the best case it runs very fast at O(n), and it is good enough to be used as part of other sorting algorithms. (For example, Timsort, used by Python's sorted(), handles small ranges with (binary) insertion sort.)
  • In terms of classification, it is a comparison sort, a stable sort and an in-place sort.

How It Works ​

This is for sorting in ascending order.

  1. Store the value at the 2nd position (index) in temp.
  2. Compare temp with the elements in front of it and insert it where it belongs.
  3. Go back to step 1, store the value at the next position in temp, and repeat.

Let's follow along with the example array [4, 2, 5, 1]. In the table, the part to the left of | is already sorted.

SteptempArray stateExplanation
Start-[4 | 2, 5, 1]The first element alone is treated as already sorted
12[2, 4 | 5, 1]4 is larger than 2, so shift it back one position and insert 2 at the front
25[2, 4, 5 | 1]4 is smaller than 5, so one comparison is enough. It stays where it is
31[1, 2, 4, 5]Shift 5, 4 and 2 back one position each, then insert 1 at the front

In Pictures ​

Insertion sort in action

Image source: GimunLee/tech-refrigerator (Apache-2.0)

Python Code ​

python
def insertion_sort(arr):
    """Insertion sort that slots values one at a time into the sorted front part (ascending)"""
    for index in range(1, len(arr)):            # 1.
        temp = arr[index]
        prev = index - 1
        while prev >= 0 and arr[prev] > temp:   # 2.
            arr[prev + 1] = arr[prev]
            prev -= 1
        arr[prev + 1] = temp                    # 3.
    return arr


print(insertion_sort([4, 2, 5, 1]))
# Output: [1, 2, 4, 5]
  1. There is nothing in front of (to the left of) the first element, so it starts from the second position (index = 1). The value at the current position is temporarily stored in temp, and the position right before it is stored in prev.
  2. If prev is not negative and the value at the previous position is larger than temp, that value is shifted back one position (arr[prev + 1] = arr[prev]) and prev moves one more step forward. The two values are not swapped; values are only shifted back, and temp is put in just once at the end.
  3. When loop 2 ends, prev points to the rightmost position holding a value less than or equal to temp. (-1 if there is no such value.) So temp goes right after it, at prev + 1.

Time and Space Complexity ​

  • In the worst case (an array sorted in reverse), like selection sort, it makes (n-1) + (n-2) + ... + 2 + 1 = n(n-1)/2 comparisons, so it is O(n²).
  • But when everything is already sorted (the best case), each element is compared with the previous element only once and done, so it is O(n).
  • When inserting or removing items one at a time in an already sorted array, it is in practice the best sorting algorithm, because apart from searching for the position, it has very little extra work (overhead).
CaseTime complexity
Best (already sorted)O(n)
AverageO(n²)
Worst (sorted in reverse)O(n²)
SpaceExtra memory O(1) (O(n) including input)
  • Space: it only shifts and inserts values within the given array, so beyond the input array it uses just O(1) more, roughly temp and prev.
  • If Big-O notation is unfamiliar, it helps to read the time complexity article first.

Pros and Cons ​

Pros ​

  • The algorithm is simple.
  • It is very efficient when most elements are already sorted.
  • It moves values within the array being sorted, so it needs no other memory space. → In-place sorting
  • It is a stable sort. It shifts a value only when it is larger than temp, so equal values never change order.
  • It is relatively faster than other O(n²) algorithms such as selection sort and bubble sort.

Cons ​

  • Its average and worst time complexity is O(n²), which is inefficient.
  • Like bubble sort and selection sort, it becomes less efficient as the array gets longer.

Difference from Selection Sort ​

Selection sort and insertion sort are similar in that after the k-th iteration, the first k elements are sorted. The differences are as follows.

AspectSelection sortInsertion sort
Meaning of the first k elementsThe k smallest of all (final positions fixed)The k elements originally at the front, sorted (may be pushed back later)
Range examined for the next elementSearches all remaining elementsSearches only as far as needed to find the position
Best caseO(n²)O(n)

That is why insertion sort runs much more efficiently.

Summary ​

ConceptPlain-language summary
Insertion sortTake out one card at a time and slot it into your already arranged hand
Shifting backValues larger than the new value step back one position each to make room
Best case O(n)Nearly sorted data finishes quickly
Difference from selection sortSelection checks everything remaining; insertion checks only as much as needed

Source: GimunLee/tech-refrigerator (Apache-2.0), code rewritten in Python

Reference: gmlwjd9405 - What is insertion sort