Created
May 17, 2017 19:42
-
-
Save claudiahdz/d46e6558e6cf4346b6a3de826baca710 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(arr) { | |
let len = arr.length, // number of items in the array | |
value, // the value currently being compared | |
i, // index into unsorted section | |
j; // index into sorted section | |
for(i = 1; i < len; i++) { | |
// store the current value because it may shift later | |
value = arr[i] | |
j = i - 1 | |
// Whenever the value in the sorted section is greater than the value | |
// in the unsorted section, shift all items in the sorted section over | |
// by one. This creates space in which to insert the value. | |
while (j >= 0 && arr[j] > value) { | |
arr[j+1] = arr[j] | |
j-- | |
} | |
arr[j+1] = value | |
} | |
return arr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment