Table of contents
Explanation
Outer Loop (
for
loop):This loop runs from the beginning of the array to the end.
The variable
start
represents the current pass through the array.At the beginning of each pass,
swapped
is set tofalse
.
Inner Loop (
for
loop):This loop iterates over the array elements from the beginning to the last unsorted element.
curr
represents the current element being compared.The condition
curr < end - start - 1
ensures that the loop only goes up to the last unsorted element, reducing the number of comparisons needed in each pass.
Comparison and Swapping:
if (arr[curr] > arr[curr + 1])
checks if the current element is greater than the next element.If true, the elements are swapped using array destructuring:
[arr[curr], arr[curr + 1]] = [arr[curr + 1], arr[curr]]
.After a swap,
swapped
is set totrue
indicating that a swap has occurred during this pass.
Early Exit Optimization:
if (!swapped) break;
checks if no elements were swapped during the current pass.If
swapped
is stillfalse
, the array is already sorted, and the loop breaks early, improving efficiency by avoiding unnecessary passes.
Return Sorted Array:
- After the sorting is complete, the function returns the sorted array.
Code
function bubbleSort(arr) {
const end = arr.length;
let swapped;
for (let start = 0; start < end; start++) {
swapped = false;
for (let curr = 0; curr < end - start - 1; curr++) {
if (arr[curr] > arr[curr + 1]) {
[arr[curr], arr[curr + 1]] = [arr[curr + 1], arr[curr]];
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}
console.log(bubbleSort([-2, 45, 0, 11, -9])); // [ -9, -2, 0, 11, 45 ]