Bubble Sort
Explore the bubble sort algorithm by understanding its step-by-step process of sorting elements through adjacent swaps. Learn its time and space complexity, how to optimize it, and why it's a stable, in-place sorting technique useful for educational purposes and small data sets in Go programming.
We'll cover the following...
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 slice, 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 slice 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 slice. Yellow indicates the current comparison, red indicates a swap, and green indicates that a value is now ...