Insertion Sort
Build a sorted section at the front, inserting each item into place.
An insertion sort builds a sorted section at the front of the list. It takes each item in turn and inserts it into its correct place among the items already sorted. It works much like sorting a hand of playing cards.
The idea
Picture sorting cards in your hand. You pick up each new card and slide it left until it sits in the right place among the cards you have already arranged. Everything to the left stays sorted; everything to the right is still waiting.
Inserting one item
To insert an item, compare it with the sorted items to its left. Every item that is larger shifts one place to the right to make room, until the item reaches its slot. Here is the 5th pass, inserting 8 into the sorted front [3, 4, 5, 9, 15].
The sorted front has grown from five items to six. The same process repeats for every item.
Insertion sort in Python
alist = [9, 5, 4, 15, 3, 8, 11, 2]
for index in range(1, len(alist)):
current = alist[index]
pos = index
while pos > 0 and alist[pos - 1] > current:
alist[pos] = alist[pos - 1]
pos = pos - 1
alist[pos] = current
print(alist)[2, 3, 4, 5, 8, 9, 11, 15]
indexsteps through the list from the second item (index 1) to the end.currentis the item being inserted;postracks where it will go.- The
whileloop shifts each larger sorted item one place right withalist[pos] = alist[pos - 1]. - When a smaller item is reached (or the start of the list),
currentdrops intopos.
Here is the sorted front (gold) growing by one item after each pass:
What you have learned
- An insertion sort grows a sorted section at the front, inserting each new item into place.
- Larger sorted items shift right to make room for the item being inserted.
- It is efficient on small or nearly-sorted lists.
- Like bubble sort, it becomes slow on large lists.