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.
- Store the value at the 2nd position (index) in
temp. - Compare
tempwith the elements in front of it and insert it where it belongs. - 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.
| Step | temp | Array state | Explanation |
|---|---|---|---|
| Start | - | [4 | 2, 5, 1] | The first element alone is treated as already sorted |
| 1 | 2 | [2, 4 | 5, 1] | 4 is larger than 2, so shift it back one position and insert 2 at the front |
| 2 | 5 | [2, 4, 5 | 1] | 4 is smaller than 5, so one comparison is enough. It stays where it is |
| 3 | 1 | [1, 2, 4, 5] | Shift 5, 4 and 2 back one position each, then insert 1 at the front |
In Pictures

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]- 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 intemp, and the position right before it is stored inprev. - If
previs not negative and the value at the previous position is larger thantemp, that value is shifted back one position (arr[prev + 1] = arr[prev]) andprevmoves one more step forward. The two values are not swapped; values are only shifted back, andtempis put in just once at the end. - When loop 2 ends,
prevpoints to the rightmost position holding a value less than or equal totemp. (-1 if there is no such value.) Sotempgoes right after it, atprev + 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)/2comparisons, 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).
| Case | Time complexity |
|---|---|
| Best (already sorted) | O(n) |
| Average | O(n²) |
| Worst (sorted in reverse) | O(n²) |
| Space | Extra 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
tempandprev. - 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.
| Aspect | Selection sort | Insertion sort |
|---|---|---|
| Meaning of the first k elements | The 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 element | Searches all remaining elements | Searches only as far as needed to find the position |
| Best case | O(n²) | O(n) |
That is why insertion sort runs much more efficiently.
Summary
| Concept | Plain-language summary |
|---|---|
| Insertion sort | Take out one card at a time and slot it into your already arranged hand |
| Shifting back | Values 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 sort | Selection 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
