Last active
July 6, 2016 05:24
-
-
Save minsooshin/d398f5da07dfdfd1cdd21608918ab790 to your computer and use it in GitHub Desktop.
Insertion Sort Algorithm
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 insertSort(array) { | |
const n = array.length; | |
// loop from second element of array to last element | |
// because first element is first element of sorted portion | |
// at the beginning | |
for (let i = 1; i < n; i++) { | |
const element = array[i]; | |
let j = i; | |
// shift the target element to the left | |
// until the target element is greater than left one | |
while (j > 0 && array[j - 1] > element) { | |
array[j] = array[j - 1]; | |
j--; | |
} | |
array[j] = element; | |
} | |
return array; | |
} | |
console.log(insertSort([76, 23, 4, 7, 11])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment