Algorithm: Insertion Sort

Insertion sort is a simple sorting algorithm, it’s based on the idea that one element from the input elements is consumed in each iteration to find its correct position.

Even though it’s much less efficient on larger arrays than more advanced algorithms, it’s simple to implement and efficient on smaller data sets.

For our example, I’m going to be coding in JavaScript!

function insertionSort(arr) {  for(let startIdx = 0; startIdx < arr.length; startIdx++) {  }};
  • We are declaring a variable named “startIdx”, which is going to the our starting index, in our for loop.
  • In our conditional, we are saying “startIdx” is less than the length of the array that we are looping through.
  • Then we our incrementing our “startIdx”
function insertionSort(arr) {  for(let startIdx = 0; startIdx < arr.length; startIdx++) {    for(let currIdx = startIdx; currIdx > 0 && arr[currIdx-1] > 
arr[currIdx]; currIdx--) {

}
}};
  • Then we are looping again, this time we are declaring “currIdx” which is going to be our current index in the loop. This way we can have something to compare to the starting index in the first for loop.
  • In our conditional, the “currIdx” is going to be greater than 0 AND the its index is greater than it’s currIdx

All this means is this:

It’s going to compare the current element in the array to the next element in the sequence.

  • Then we are decrementing “currIdx”
function insertionSort(arr) {  for(let startIdx = 0; startIdx < arr.length; startIdx++) {    for(let currIdx = startIdx; currIdx > 0 && arr[currIdx-1] > 
arr[currIdx]; currIdx--) {

let temp = arr[currIdx]
arr[currIdx] = arr[currIdx-1]
arr[currIdx-1] = temp
} }};

In our 2nd for loop block, we are declaring variable named temp and setting that equal to current index. Then setting the current index to equal it self but by -1. And then setting the current index -1 to equal temp.

And that’s it! Thank you!

I’m a Software Engineer who is always learning something new!

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