Insertion Sort in JavaScript

Just want the code? Scroll all the way down for two version of the code.

  1. Without comments (just plug and use).
  2. With comments to have better understanding of the code.

What is Insertion Sort

Insertion sort is a simple sorting algorithm that sorts the elements one at a time. It is more efficient in practice when compared with other simple quadratic algorithms like bubble sort or selection sort. It can even outperforms more advanced algorithms like quick sort or merge sort on a small list.

Very often you’ll see a sort button uses two kinds of sorting algorithms depending on the size/length of the list. If it’s large they’ll common use quick or merge sort. While in a small array, they typically will use insertion sort. For example, when programming in JavaScript in google chrome, it uses Quick Sort and Insertion Sort depending on the size of the array.

Steps to Sort using Insertion Sort

Implementing Insertion Sort just needs just 2 basic loops.

  1. Start a loop from the left side of the array, checking each elements to sort them in place.
  2. Then do a second loop against all the elements on the left to insert the element in the correct location.

That’s it, easy and simple.

GIF showing insertion sort

Insertion Sort in JavaScript

Before we start, we need to note that Insertion Sort is an destructive function, as it will modify the array you put into it. If you don’t want to modify the original array, make sure to use the spread operator to create a new variable before injecting this sorting algorithm.

We now start by creating a for loop to go through all the elements in the array to check them against the left side to inject it in the correct location.

Then we want to compare it with all the elements on the left of the key until we find an element that is smaller than our key or until we reach the beginning of the array.

While we are comparing the key with every element, if the element isn’t smaller than the key, we want to shift it one step to the right, to give room for the key to insert into the correct location.

And lastly we just need to insert the key into the correct location

Just Here for the Code?

Version 1: Just the functions without any comments

Version 2: With comments

Just a student at flatiron