How Bubble Sort Works
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This pass-through is repeated until the list is sorted. It is one of the simplest sorting algorithms to understand and implement.
Starting from the first element, compare each pair of adjacent elements and swap them if the left one is greater. After each full pass, the largest unsorted element 'bubbles up' to its correct position. Repeat until no swaps are needed.
Complexity
- Time
- O(n²)
- Space
- O(1)
- Stability
- stable
When to Use Bubble Sort
- Educational purposes and learning to sort
- Nearly sorted small datasets
- When simplicity matters more than speed