Bubble Sort
Bubble Sort
Each pass "bubbles up" the largest unsorted element to its correct position, hence the name
"Bubble Sort."
Let’s go through a basic demo of Bubble Sort with a simple list of numbers:
List: [5, 2, 9, 1, 5]
Step-by-Step
1. First Pass:
- Compare `5` and `2`: `5` is bigger, so swap them → `[2, 5, 9, 1, 5]`
- Compare `5` and `9`: `5` is not bigger, so no swap
- Compare `9` and `1`: `9` is bigger, so swap them → `[2, 5, 1, 9, 5]`
- Compare `9` and `5`: `9` is bigger, so swap them → `[2, 5, 1, 5, 9]`
Now, the largest element (`9`) is in the correct position at the end.
2. Second Pass:
- Compare `2` and `5`: `2` is not bigger, so no swap
- Compare `5` and `1`: `5` is bigger, so swap them → `[2, 1, 5, 5, 9]`
- Compare `5` and `5`: They are equal, so no swap
3. Third Pass:
- Compare `2` and `1`: `2` is bigger, so swap them → `[1, 2, 5, 5, 9]`
- Compare `2` and `5`: `2` is not bigger, so no swap
After a few passes, every element has "bubbled up" to its correct position!