Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created February 3, 2013 09:57
Show Gist options
  • Save hiroshi-maybe/4701110 to your computer and use it in GitHub Desktop.
Save hiroshi-maybe/4701110 to your computer and use it in GitHub Desktop.
Insertion sort implemented with Javascript.
var insertionSort = function(array) {
for(var i=1, length=array.length; i<length; i+=1) {
var insertion = array[i], j=i;
if (insertion < array[i-1]) {
do {
array[j] = array[j-1];
j-=1;
} while (array[j] > insertion && j > 0)
array[j] = insertion;
}
}
return array;
};
console.log(insertionSort([8,4,3,7,6,5,2,1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment