Bubble Sort

  • Compare two adjacent elements and swap places if the latter is larger than the previous.
  • The last element is the largest in the first round.
  • After an n-1 round (length-1 of the array), we are done sorting all the numbers
  • Time complexity: O (n²)
const bubbleSort = (arr) = >{
  if(! arr.length)return [];
  for(let i =0; i<arr.length-1; i++){let flag = false;
    for(let j=0; j<arr.length-1-i; j++){if(arr[j]>arr[j+1]) {let temp = arr[j+1];
        arr[j+1] = arr[j];
        arr[j] = temp;
        flag = true; }}if(! flag)break; 
  }
  console.log(arr)
}
const bubbleArray = [5.2.3.5.7.9.1.2];
bubbleSort(bubbleArray);
Copy the code

🤔 thinking, how to optimize bubble sort?