devnieL
1/14/2012 - 12:07 AM

INSERTION-SORT

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]));