Skip to content

Instantly share code, notes, and snippets.

@claudiahdz
Created May 17, 2017 19:42
Show Gist options
  • Save claudiahdz/d46e6558e6cf4346b6a3de826baca710 to your computer and use it in GitHub Desktop.
Save claudiahdz/d46e6558e6cf4346b6a3de826baca710 to your computer and use it in GitHub Desktop.
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