Skip to content

Instantly share code, notes, and snippets.

@flowck
Last active July 14, 2021 07:44
Show Gist options
  • Save flowck/cf683dafdb4cdbb6079411fdf06136d2 to your computer and use it in GitHub Desktop.
Save flowck/cf683dafdb4cdbb6079411fdf06136d2 to your computer and use it in GitHub Desktop.
Insertion sort
"use strict";
function insertionSort() {
var list = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
for (var i = 0; i < list.length; i++) {
var key = list[i];
var prevIndex = i - 1;
while (prevIndex >= 0 && list[prevIndex] > key) {
list[prevIndex + 1] = list[prevIndex];
console.log(list);
prevIndex--;
}
list[prevIndex + 1] = key;
console.log("\n");
}
return list;
}
console.log(insertionSort([9, 8, 100, 5, 1, 9, 11]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment