Imagine a bunch of bubbles in a glass of soda, and they tend to rise to the top.
Bubble sort works similarly — it compares adjacent items in a list and swaps them if they are in the
wrong order, causing larger items to "bubble up" to the end of the list step by step.
A simple way to think about it:
1. Start at the beginning of the list.
2. Compare the first two items.
- If the first is bigger than the second, swap them.
3. Move one step forward and compare the next pair.
4. Keep doing this until end of the list is reached
- By the end of this pass, the largest number will be at the very end.
5. Repeat the process for the remaining items (excluding the last sorted ones).
6. Keep doing this until no more swaps are needed, meaning the list is sorted.
CLASSWORK Suppose you have these numbers: `[5, 2, 8, 1, 4]`
- First pass:
- Compare 5 and 2 → swap → `[2, 5, 8, 1, 4]`
- Compare 5 and 8 → no swap
- Compare 8 and 1 → swap → `[2, 5, 1, 8, 4]`
- Compare 8 and 4 → swap → `[2, 5, 1, 4, 8]` (8 is now at the end)
- Second pass:
- Compare 2 and 5 → no swap
- Compare 5 and 1 → swap → `[2, 1, 5, 4, 8]`
- Compare 5 and 4 → swap → `[2, 1, 4, 5, 8]`
- Continue until no swaps are needed…………………………………………………….Work out
Advantages of Bubble Sort:
Bubble sort is easy to understand and implement.
It does not require any additional memory space.
It is a stable sorting algorithm, meaning that elements with the same key value maintain
their relative order in the sorted output.
Disadvantages of Bubble Sort:
Bubble sort has a time complexity of O(n 2) which makes it very slow for large data sets.
Bubble sort has almost no or limited real world applications. It is mostly used in academics
to teach different ways of sorting.
In summary: Bubble sort repeatedly compares and swaps neighboring items until the whole list is
sorted, just like bubbles rising to the surface. It's simple but not the most efficient for large lists.