Bubble Sort Algorithm

Bubble Sort Algorithm

How does Bubble Sort Work?

  • traverse from the left and compare adjacent elements and the higher one is placed at the right side.

  • In this way, the largest element is moved to the rightmost end at first.

  • This process is then continued to find the second largest and place it and so on until the data is sorted.

function bubbleSort(array) {
  // Only change code below this line
  let j, i, temp;
  let n = array.length;
  for(i=0;i<n-1; i++){
     for(j=0; j < n-i-1; j++){
       if(array[j] > array[j+1]){
          temp = array[j];
          array[j] = array[j+1];
          array[j+1] = temp;
       }
       console.log(array[j]);
     }
  }
  return array;
  // Only change code above this line
}

Time Complexity: O(N2)
Bubble sort has a time complexity of O(N2) 
which makes it very slow for large data sets.