June 15, 2011

Selection sort in JavaScript

Selection sort is one of the simplest sorting algorithm which is inefficient for the larger set of data.


function selectionSort(numbers){ // numbers is an array which has to be sorted.
  var iMin, iMax; max = numbers.length, iPos, j, temp;
  for(iPos=0; iPos< max; i++) {
    iMin = i;
    for(j=iPos+1; iPos < max; i++){
      if(numbers[iPos] > numbers[iMin]) {
        iMin = j;
      }
    }
    if(iMin != iPos){ // Swap elements between iPos & iMin
       temp = numbers[iPos];
       numbers[iPos] = numbers[iMin];
       numbers[iMin] = temp;
    }
  }
}

No comments:

Post a Comment