Skip to content

Instantly share code, notes, and snippets.

@devniel
Created January 14, 2012 00:07
Show Gist options
  • Save devniel/1609474 to your computer and use it in GitHub Desktop.
Save devniel/1609474 to your computer and use it in GitHub Desktop.
INSERTION-SORT
/*
INSERTION-SORT(A)
for j=2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence A[1..j-1]
i=j-1
while i>0 and A[i] > key
A[i+1] = A[i]
i = i-1
A[i+1] = key
*/
function insertionSort(a){
for(var j=1;j<a.length;j++){
var key = a[j];
for (i=j-1;i >= 0 && a[i] > key;i--){
a[i + 1] = a[i];
}
a[i+1] = key;
}
return a;
}
function insertionSort(a){
for(var j=1;j<a.length;j++){
var key = a[j];
console.log("key",key);
var i = j-1;
console.log("i",i);
while(i>=0 && a[i] > key){
a[i+1] = a[i];
i = i-1;
}
a[i+1] = key;
}
return a;
}
console.log(insertionSort([5,2,4,6,1,3]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment