DEV Community

Cover image for Understanding the Insertion Sort Algorithm
Marcos Nikel
Marcos Nikel

Posted on

Understanding the Insertion Sort Algorithm

In our day-to-day JavaScript programming, when we use the .sort() method, there's a whole algorithm running behind the scenes. However, it's unlikely that Insertion Sort is the algorithm being used. But why is that?

  • There are various sorting algorithms available, such as Insertion Sort, Quick Sort, Merge Sort, Selection Sort, Bubble Sort, and many others. Each of them has different time and space complexities.

Insertion Sort happens to be one of the less efficient ones, but why?

In terms of complexity, Insertion Sort has a time complexity of O(nĀ²) in most cases and a space complexity of O(1), which is good. However, considering a time complexity of this magnitude, there are sorting algorithms that achieve a time complexity of O(n log n), which is better than O(nĀ²).

So, how does this algorithm work?

  1. Initially, we consider the first element of the list as a sorted list with a single element.

  2. Next, we move on to the next element in the unsorted list.

  3. We compare the current element with the elements in the sorted list, from right to left, until we find the correct position to insert the element.

  4. During the comparison, if an element in the sorted list is greater than the current element, it is shifted one position to the right to make space for the insertion.

  5. We repeat steps 3 and 4 until all elements in the unsorted list are inserted into the sorted part of the list.

  • This process continues until all elements are in the sorted list, resulting in a completely ordered list. Insertion Sort is an efficient sorting algorithm for small lists or partially sorted lists. However, its performance significantly deteriorates for very large lists.

Below, I provide an example implementation of this algorithm, including an auxiliary function called swap() responsible for swapping elements.

Code example

Top comments (0)