Created
August 26, 2016 12:50
-
-
Save alexeykomov/70da70bd2a0fc7d4551b8054b03463f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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