Skip to content

Instantly share code, notes, and snippets.

@easonhan007
Created September 2, 2014 03:49
Show Gist options
  • Save easonhan007/e96572311eb45854043f to your computer and use it in GitHub Desktop.
Save easonhan007/e96572311eb45854043f to your computer and use it in GitHub Desktop.
insert sort using javascript and run it using node
// insert sort implement using javascript
function print(what) {
console.log(what);
}
function insertSort(array) {
var currentPos, before;
for(currentPos = 1; currentPos < array.length; currentPos++) {
var current = array[currentPos];
before = currentPos - 1;
while(array[before] > current) {
array[before + 1] = array[before];
before--;
}
array[before + 1] = current;
}
}
// test insert sort
to_sort = [3, 9, 1, 4, 1];
insertSort(to_sort);
print("before sort");
console.log(to_sort);
print("after sort");
console.log(to_sort);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment