Bubble Sort, explained step by step
Bubble Sort is a straightforward, beginner-friendly sorting algorithm that repeatedly steps through the list. In every pass, it compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. It is named for the way larger elements "bubble" to the top (or end) of the list with each iteration.
Intuition: Imagine bubbles rising to the surface of water. Each pass through the array "bubbles" the largest unsorted element to its correct position at the end.
How it works
- Compare adjacent elements (starting from index 0).
- If the first is greater than the second, swap them.
- Move to the next adjacent pair and repeat until the end of the array.
- The largest element will "bubble up" to the last position, which is now sorted.
- Repeat the entire process for the remaining unsorted elements until no swaps are needed.
Complexity
- Best: O(n)
- Average: O(n²)
- Worst: O(n²)
- Space: O(1)
- Stable: yes
When to use it
Educational purposes and very small arrays. Never use in production due to O(n²) worst-case.
Interview questions
- What is the best-case time complexity of Bubble Sort?
- How would you detect if an array is already sorted in one pass?
- Why is Bubble Sort considered stable?