Bubble Sort
Idea Like You Are 10
Imagine numbers are standing in a line.
You look at two neighbors at a time:
- If they are in the wrong order, swap them
- Keep doing that again and again
The biggest number keeps moving right, like a bubble floating up in water.
Small Example
Sort:
Pass 1:
Now the biggest number, 8, is in the correct place.
Pass 2:
Pass 3:
Sorted.
Diagram
Algorithm
- Compare neighboring elements
- Swap if left is bigger than right
- After one full pass, the biggest unsorted element reaches the end
- Repeat for the remaining unsorted part
Pseudocode
Time Complexity
| Case | Time |
|---|---|
| Best | O(n) |
| Average | O(n^2) |
| Worst | O(n^2) |
Why This Time Complexity?
Best Case: O(n)
If the list is already sorted, we make one pass, see no swaps, and stop.
That means we check about n elements once.
Average And Worst Case: O(n^2)
In the average or bad case, we may do:
- about
npasses - and in each pass, about
ncomparisons
So it becomes:
Space Complexity
O(1) because it sorts in the same array and uses only a tiny amount of extra memory.
Performance
- Very easy to understand
- Very slow for big lists
- Good for learning, not usually for real large programs
When To Use
- When you are just starting to learn sorting
- When the list is tiny
- When you want a simple idea, not the fastest one