When the array is already sorted, bubble sort makes only one pass through the array with no swaps.
For random arrays, bubble sort still requires quadratic time.
When the array is sorted in reverse order, bubble sort must make the maximum number of comparisons and swaps.
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
// If no swapping occurred in this pass,
// array is sorted
if (!swapped) break;
}
return arr;
}