Created
January 14, 2012 00:07
-
-
Save devniel/1609474 to your computer and use it in GitHub Desktop.
INSERTION-SORT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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