Imagine a line of pupils standing in a jumbled order, and you want them shortest-to-tallest. You can't see the whole line at once, so you use a simple rule: look at just two people standing next to each other, and if the taller one is in front, ask them to swap places. Then shuffle one step along and check the next pair. Keep sweeping down the line, again and again, and — almost like magic — everyone drifts into order.
That is bubble sort, one of the first sorting algorithms every computer scientist meets. Its whole idea is built from one tiny action repeated over and over:
The name comes from that last picture: on every pass the biggest remaining value rises to the top of the list like a bubble rising through water.
Let's sort the little list
Notice how the
The heart of bubble sort is swapping two values. You might think you can just write
a = b and b = a — but that loses one of the values! The
moment you copy b into a, the old a is gone, so
b = a just copies b back onto itself. You end up with two copies of
b and no a at all.
The fix is a temporary variable — a spare box to hold one value while you move the other. It's exactly like swapping the drinks in two glasses: you need a third, empty glass to pour one into first. Run this and see the swap work correctly:
Now we put the pieces together. We need an inner loop that makes one pass, comparing
each adjacent pair list[j] and list[j + 1] and swapping when they're out of
order, wrapped in an outer loop that repeats those passes. Run it and read the
console.log after each pass — you'll see the largest values marching to the right:
Two details make it efficient. The inner loop stops at length - 1 - i, not
length - 1: because pass >, so equal values are left alone — which keeps the sort stable
(a nice bonus you'll meet again later).
There's one more trick that makes bubble sort clever rather than plodding. If a whole pass goes by
without a single swap, the list must already be in order — so we can stop right away
instead of grinding through the remaining passes. We track this with a swapped flag:
Try feeding it a list that's already sorted, like [1, 2, 3, 4, 5]: it makes just
one pass, sees no swaps, and stops immediately. That "best case" is the fastest bubble sort ever gets.
Bubble sort is wonderfully easy to understand — but it is slow. For
a list of
The other classic trap is the swap itself. If you try to exchange two values with just
list[j] = list[j + 1] followed by list[j + 1] = list[j], you
overwrite and lose one value — both slots end up holding the same number. Always use a
temporary variable (the three-line swap above) so nothing is thrown away.