Repeatedly swap adjacent out-of-order pairs; each pass floats the next-largest value to the end.
Bubble sort is the simplest sort to picture: walk the list comparing each pair of neighbours, and swap them whenever they're out of order. Like bubbles rising in liquid, the heaviest value 'sinks' to the right on every pass — so after enough passes, everything has settled into place. It's slow, but it's where almost everyone starts.
Sweep left to right comparing arr[i] with arr[i+1]. The largest value you meet keeps winning its comparisons and gets carried along until it reaches the far right — so one full pass guarantees the maximum lands in its final spot. The next pass only needs to reach one position earlier, and so on.
O(n) on already-sorted or nearly-sorted input.function bubbleSort(arr) {
for (let end = arr.length - 1; end > 0; end--) {
let swapped = false;
for (let i = 0; i < end; i++) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
if (!swapped) break; // already sorted — early exit
}
return arr;
}