*Insert Sorting Algo Here*

Understanding Insertion Sort

My journey into data structures and algorithms has arrived at its next sorting algorithm stop, welcome to Insertion Sort! As a quick reminder, a sorting algorithm arranges the elements in a collection of data in the correct order. One of the simplest algorithms used is Insertion Sort. Insertion Sort is not only a sorting algorithm but it is also a comparison sort.

A comparison sort is any sorting algorithm that compares the value of the current element you are trying to place to the other values within the same array of data that is being sorted. Comparison sorting algorithms only work where a “less-than” relationship is defined. A comparison sort accomplishes this by working with one element at a time and places each item into the right order in the array.

How Insertion Sort works

He is a quick example of how Insertion Sort works.

Example Array [6,4,1,7,9]

Insertion sort will assume the first element 6 is already sorted, and then will move on to the next element which is 4and compare it to the previous element of 6, and if 4 is less than 6, then that means 4should be inserted right before 6, when the next element is greater than 6, then that element will remain in its position. The “less-than” relationship is defined and that is how the sorted array gradually grows one element at a time.

Steps of Insertion Sort

  • Start with the second element of the array.
  • Insertion Sort then compares it to the element before it, and swap if that element is less than the one before it.
  • Insertion Sort will then continue to the next element, and continue iterating through the left part of the array, which is already sorted, and insert that current element in its correct place in the sorted portion.
  • This process is repeated until the array is sorted, and of course, make sure you return the sorted array.

Insertion Sort: The Code!

 array = [6,4,1,7,9]
const insertion = array => {
const lenght = array.length;
for (let i = 0; i < length; i++) {
let element = array[i];
let j;

for (j = i - 1; j >= 0 && array[j] > element; j--) {
array[j + 1] = array[j];
}
array[j + 1] = element;
}
return array;
};
insertion(array) =>> [1,4,6,7,9]

*Insert Happy Web Dev Here*

Full-Stack Software Engineer / New York City / www.danielcreyes.dev