Bubble Sort
Explore how bubble sort organizes data by repeatedly comparing and swapping neighboring elements. Understand the algorithm's passes, its best and worst-case time complexities, and how optimization stops unnecessary steps. This lesson helps you grasp bubble sort's simplicity, stability, and when to apply it effectively in Python.
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 ...