← Return to blogs

Insertion Sort

Insertion Sort is an efficient algorithm for sorting a small number of elements. The most common illustration used for demonstrating insertion sort is playing cards. We start with an empty left hand and the cards face down on the table. We then remove one card at a time from the table and insert it into the correct position in the left hand. To find the correct position of the card, we compare it with each of the cards already in hand.

The Code

In the code snippets above, we see an implementation of Insertion Sort. Within our for loop, the temp variable, key, tracks the current element. We also keep track of the 'j - 1' element using a variable 'i'. If the element in i is greater than the key, then we have to swap those elements by setting a[i + 1] (or j in the first iteration) to the value of a[i]. This pattern continues until there are no more values before 'j' that are greater than itself. Finally, using our temp variable (key), we set that equal to the current position of 'j'. That is insertion sort! (Note: The purpose of a insertion sort is to sort an array in-place. But I stored the sorted array in a variable called 'sorted' in some of the code snippets to help output the array to the user. Just a personal preference to avoid creating a util function.)

The Analysis

All things considered, Insertion Sort is pretty inefficient. It works best when working with smaller datasets. This is due to the double loop required for the algorithm to work. However, it is still an effective in-place sorting algorithm.

Time Complexities:

Space Complexity

The Takeaway

Insertion Sort is the first sorting algorithm I learned about in my data structures and algorithms course. Because of that, it holds a special place in my heart. Conceptually, it is quite simple to understand, but actually writing the code for it is a different story. Yes, it only requires a few lines of code, but imagine having to write this out during an interview by memory? Unless you have researched and put a good amount of thought into this algorithm, writing this from scratch can be tricky!