June 15, 2011

Insertion sort in JavaScript

Insertion sort is efficient algorithm to sort the substantially sorted data set.

function insertionSort(numbers){ // numbers is an array which has to be sorted.
  var max = numbers.length, i, j, temp;
  for(i=0; i< max; i++) {
    temp = numbers[i];
    j = i-1;
    while(temp < numbers[j] && j >= 0) {
       numbers[j+1] = numbers[j];
       j--;
    }
    numbers[j+1] = temp;
  }
}

No comments:

Post a Comment