Bubble Sort
Explore how the bubble sort algorithm organizes data by repeatedly swapping adjacent elements to sort arrays. Understand its process, time and space complexities, and practical JavaScript implementation. Learn its advantages, limitations, and when it is suitable to use bubble sort in sorting tasks.
Imagine a line of students holding numbered cards. The teacher wants them arranged in ascending order. The teacher starts on the left, compares two neighboring students at a time, and swaps them whenever the larger number is standing in front of the smaller one.
After one complete walk from left to right, the largest card is guaranteed to end up at the far right. After the next walk, the second-largest card reaches its final position. This repeated neighbor swapping is exactly how Bubble Sort works.
Bubble sort is a comparison-based sorting algorithm that repeatedly scans the collection, compares adjacent elements, and swaps them when they are out of order. After each pass, the largest element in the unsorted region moves to its correct final position.
Why is it called bubble sort?
On each pass, larger values rise toward the end of the list, the way air bubbles rise to the surface of water.
How bubble sort works
Bubble Sort uses two nested loops:
Inner pass: Compare neighbors at indices
jandj + 1.Outer pass: Repeat that process until the whole list is sorted.
On pass one, the largest element is pushed to the end. On pass two, the next-largest element is pushed to the second-to-last position. That means the unsorted portion keeps shrinking. After each pass, one more element is placed in its correct final position.
Interactive animation
Use the animation below to watch bubble sort on the same list. Yellow indicates the current comparison, red indicates a swap, and green indicates that a value is now in its final position.
Algorithm
Before writing JavaScript code, read through the algorithm and connect each step to the trace above.
Start from the beginning of the list.
Compare the first element with the next element. If they are in the wrong order, swap ...