Last active
September 29, 2016 15:36
-
-
Save taravancil/2ae627050856dde5d221ca810310e26f to your computer and use it in GitHub Desktop.
An implementation of insertion sort
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
// 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