June 14, 2011

Bubble sort in JavaScript

Bubble sort is a simple sorting algorithm also known as sinking sort that works by iterating the given array in a nested loop. Here is the sample code for bubble sorting in JavaScript.

function bubbleSort(numbers){
  var max = numbers.length, i, j, temp;
  for(i=0; i< max; i++) {
    for(j=i+1; j < max; j++) {
      if(numbers[i] > numbers[j]) {
        temp = numbers[i];
        numbers[i] = numbers[j];
        numbers[j] = temp;
    }
   }
  }
}

No comments:

Post a Comment