Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created January 12, 2014 06:12
Show Gist options
  • Save jack-wong-build/8381583 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8381583 to your computer and use it in GitHub Desktop.
Insertion sort in javascript
var insertionSort = function(array){
var target;
var sortedIndex = 0;
var targetIndex;
for(var i = 0; i < array.length; i++){
target = array[i];
targetIndex = i;
for(var j = i; j >= sortedIndex; j--){
if (array[j] > target){
array[targetIndex] = array[j];
array[j] = target;
targetIndex--;
}
}
}
return array;
}
//console.log(insertionSort([2, 1, 3, 5, 4, 7, 9, 21, 10, 5]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment