Skip to content

Instantly share code, notes, and snippets.

@alexeykomov
Created August 26, 2016 12:50
Show Gist options
  • Save alexeykomov/70da70bd2a0fc7d4551b8054b03463f3 to your computer and use it in GitHub Desktop.
Save alexeykomov/70da70bd2a0fc7d4551b8054b03463f3 to your computer and use it in GitHub Desktop.
function insertionSort(aInput) {
const output = [...aInput];
let lastSortedIndex = 0;
for (let counter = 1; counter < output.length; counter++) {
const itemInQuestion = output[counter];
let newIndexToPlace = counter;
for (let sortedIndex = counter - 1; sortedIndex >= 0; sortedIndex--) {
if (itemInQuestion < output[sortedIndex]) {
output[sortedIndex + 1] = output[sortedIndex];
newIndexToPlace = sortedIndex;
}
}
if (newIndexToPlace != counter) {
output[newIndexToPlace] = itemInQuestion;
}
}
return output;
}
console.log(insertionSort([18, 3, 4, 2, 1, 20, 13]));
console.log(insertionSort([3, 1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment