DEV Community

Cover image for Insertion Sort
Sudharsanan Ravichandran
Sudharsanan Ravichandran

Posted on

2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
ghanendrayadav profile image
Ghanendra Yadav

very nice explanation

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay