Skip to content

Instantly share code, notes, and snippets.

@venil7
Created April 27, 2015 16:39
Show Gist options
  • Save venil7/cb63567d7b7b8f213551 to your computer and use it in GitHub Desktop.
Save venil7/cb63567d7b7b8f213551 to your computer and use it in GitHub Desktop.
insert sort implementation
var array = [1,7,5,9,0,4,12,56,7,0,45,8,2,3,6,7,8,1,5,0];
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
var insertion_sort = function (unsorted) {
for(var i=1;i<unsorted.length;i++) {
var current = unsorted[i];
var j = i - 1;
while(j >= 0) {
var compare = unsorted[j];
if (current > compare) {
break;
}
j--;
}
unsorted = unsorted.move(i, j+1);
}
return unsorted;
};
console.log(insertion_sort(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment