Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Created January 31, 2018 20:00
Show Gist options
  • Save ti-ka/4a3766780cfb9ecb257cc4aef55e14d1 to your computer and use it in GitHub Desktop.
Save ti-ka/4a3766780cfb9ecb257cc4aef55e14d1 to your computer and use it in GitHub Desktop.
Insertion Sort https://jsbin.com/sezuqan
// Insertion Sort
// Insertion sort is a comparison-based algorithm that builds a final sorted array one element at a time.
// It iterates through an input array and removes one element per iteration, finds the place the element belongs in the array, and then places it there.
// https://brilliant.org/wiki/sorting-algorithms/
var array = [47,59,98,98,91,10,0,9,14,12]
console.log(insertionSort(array))
function insertionSort(array) {
for (var i = 1; i < array.length; i++) {
for (var j = i; j > 0; j--) {
if (array[j] < array[j-1]) {
//swap
var temp = array[j]
array[j] = array[j-1]
array[j-1] = temp
}
}
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment