DEV Community

Cover image for Insertion Sort
Sudharsanan Ravichandran
Sudharsanan Ravichandran

Posted on

Insertion Sort

This is my second post on Sorting algorithms.

We will see how Insertion Sort works

Insertion sort is another naive sorting approach which can't be used for large data sets. But, if you understand the crux of how it works under the hood. It's easy to implement.

Below is the Pseudocode for the sorting algorithm

Pseudocode

  1. Element at the very first index is assumed sorted
  2. You pick the element at the second index
  3. Compare the element with the sorted subarray list (one element at a time)
  4. If element compared within the sorted subarray list is bigger than the current you will shift them one place to the right.
  5. You will repeat the above process until either you reach the left end of the array or if the element compared with is less than the current element.
  6. Repeat the process until all elements are sorted.

I got this beautiful visual representation of how it works in a nutshell.

Please click on the below reference link to check it out.

https://tutorialsbookmarks.com/wp-content/uploads/2019/08/Insertion-sort-example.gif

Below is the source code implemented in JavaScript.

This is not a pure function-based implementation!

Insertion Sort JS

Hope you like this, please share your comments and I am looking forward to any optimizations that can be done here.

On my next post, we will see the Selection Sort and also understand how it's similar to the Insertion sort we saw above.

For this content, I got an awesome video reference that I can't wait to share.

See you in the next post!

Thanks,
Sudharsanan Ravichandran

Top comments (1)

Collapse
 
ghanendrayadav profile image
Ghanendra Yadav

very nice explanation