Advanced JavaScript Training
Bubble Sort

Bubble Sort

  • Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order
  • While not efficient for large datasets, it's easy to understand and implement.
  • It has a time complexity of O(n^2), making it less suitable for large arrays.
<pre style='text-align: left;'>

function bubbleSort(arr) { let n = arr.length; let swapped;

   do {
      swapped = false;
      for (let i = 0; i < n - 1; i++) {
          if (arr[i] > arr[i + 1]) {
             // Swap arr[i] and arr[i+1]
             let temp = arr[i];
             arr[i] = arr[i + 1];
             arr[i + 1] = temp;
             swapped = true;
        }
    }
} while (swapped);

return arr;

} const unsortedArray = [64, 34, 25, 12, 22, 11, 90]; const sortedArray = bubbleSort(unsortedArray);

Have a doubt?
Post it here, our mentors will help you out.