Insertion Sort in JavaScript

  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.

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.
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.

Just Here for the Code?

Version 1: Just the functions without any comments

Version 2: With comments

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store