ArticlesSearch and sort

Search and sort

Bubble sort

Swap neighbours until the array settles. Easy to remember, and quadratic. A contrast, not the sort to reach for.

Bubble sort walks the array and swaps neighbours that are out of order, then does it again, until a pass makes no swaps. Larger values drift toward the end. It is easy to remember and easy to get right, which is why it shows up in a first explanation of sorting.

It is also O(n²). Each pass can look at every remaining pair. You keep it as a contrast, not as the sort you defend in an interview or in a hot loop. When you need a sort whose cost you can draw, merge sort stays O(n log n) in every case you will implement here.

If you call the language's sort instead of writing one, know what you are calling. JavaScript's default sort compares values as strings unless you pass a compare function. For numbers, pass a function that subtracts. The name sort does not mean the numeric order you assumed.