Skip to content

Instantly share code, notes, and snippets.

@taravancil
Last active September 29, 2016 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taravancil/2ae627050856dde5d221ca810310e26f to your computer and use it in GitHub Desktop.
Save taravancil/2ae627050856dde5d221ca810310e26f to your computer and use it in GitHub Desktop.
An implementation of insertion sort
// Average case O(n^2)
function insertionSort (arr) {
// Begin at position 1, because we need to compare the element at
// that position to the previous element
for (let i = 1; i < arr.length; i++) {
let j = i
// If the prior element is greater than the current element (arr[j]), swap
while (j > 0 && arr[j-1] > arr[j]) {
// Storing the tmp variable requires O(1) memory space
let tmp = arr[j]
arr[j] = arr[j-1]
arr[j-1] = tmp
j--
}
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment