-
-
Save easyrider/06eb7df43a14ec18f1dd7194ff12e919 to your computer and use it in GitHub Desktop.
Insertion Sort in JavaScript
This file contains hidden or 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
var insertionSort = function (a) { | |
// Iterate through our array | |
for (var i = 1, value; i < a.length; i++) { | |
// Our array is split into two parts: values preceeding i are sorted, while others are unsorted | |
// Store the unsorted value at i | |
value = a[i]; | |
// Interate backwards through the unsorted values until we find the correct location for our `next` value | |
for (var j = i; a[j-1] > value; j--) { | |
// Shift the value to the right | |
a[j] = a[j-1]; | |
} | |
// Once we've created an open "slot" in the correct location for our value, insert it | |
a[j] = value; | |
} | |
// Return the sorted array | |
return a; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment