Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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