Skip to content

Instantly share code, notes, and snippets.

@benfluleck
Created April 21, 2019 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfluleck/34c96aca09fa004069a67746b8d66449 to your computer and use it in GitHub Desktop.
Save benfluleck/34c96aca09fa004069a67746b8d66449 to your computer and use it in GitHub Desktop.
Insertion Sort
function swapNumbers(items, leftIndex, rightIndex){
const temp = items[leftIndex];
items[leftIndex] = items[rightIndex];
items[rightIndex] = temp;
}
function insertionSort(array = []) {
for(let i = 0; i < array.length; i++) {
let currentIndex = i
while(currentIndex > 0 && array[currentIndex] < array[currentIndex - 1]) {
swapNumbers(array, currentIndex, currentIndex - 1)
currentIndex--
}
}
return array
}
@benfluleck
Copy link
Author

Order: O(n^2)
Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find its correct position i.e, the position to which it belongs in a sorted array.

It iterates the input elements by growing the sorted array at each iteration. It compares the current element with the largest value in the sorted array. If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position. This is done by shifting all the elements, which are larger than the current element, in the sorted array to one position ahead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment