Blog

JavaScript Bubble Sort Functions Using a Do/While Loop and Nested For Loops
Posted on July 13, 2015 in Algorithms, JavaScript by Matt Jennings

Bubble Sort Definition

Per this video, a Bubble Sort is where an array is looped through and the largest array element “bubbles” to or is placed in the array as the last element. Then, the array is looped again so that the second largest array element is placed in the array as the second to last element and so on.

Finally, the array will be sorted with the array elements being in lowest to highest order.

Do/While Bubble Sort

function bubbleSortDoWhile(arr) {
  var swap;
  
  // The "do" statement executes at least once if the 
  // "while" statement is true or false
  do{
    swap = false;
    
    for(var i = 0; i < arr.length; i++) {
      if(arr[i] > arr[i + 1]) {
        
        // 3 lines below swaps array indices
        // next to each other if the lower index element
        // is greater than the higher index element
        temp = arr[i];
        
        arr[i] = arr[i + 1];
        
        arr[i + 1] = temp;
        
        swap = true;
      }
    }
  }
  // The "while" statement continues execution ONLY
  // when the "swap" variable is true
  while(swap);
  
  console.log(arr); 
}

var x = [1, -3, 0, 9, -4];

// Array elements are outputted from smallest to highest numbers
bubbleSortDoWhile(x);

Nested For Loops Bubble Sort with Comments

var arr = [5, 2, 6, 3, 10, 1];

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

console.log(bubbleSort(arr));
// [1, 2, 3, 5, 6, 10]

Nested For Loops Bubble Sort with Minimal Comments

function bubbleSort(arr) {

  if(arguments.length !== 1 || !Array.isArray(arr)) {
    throw new Error();
  }
  
  var numbersSwapped;

  for(var i = 0; i < arr.length - 1; i++) {
    numbersSwapped = false;

    for(var j = 0; j < arr.length - 1; j++) {
      if(arr[j] > arr[j + 1]) {
        numbersSwapped = true;
        var temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }  
    }
    
    if(!numbersSwapped) {
      return arr;
    }
    
  }
  return arr;
}

var x = [1, 4, 90, -2, 70, 71, 66, 65, -5];

// Output for code below is:
// [-5, -2, 1, 4, 65, 66, 70, 71, 90]
console.log(bubbleSort(x));

Leave a Reply