What is Bubble Sort?
Bubble Sort walks through the array from one end to the other, checking each pair of neighboring values as it goes and swapping them whenever they're in the wrong order. One full walkthrough is called a pass, and the array keeps getting passed over again until a pass finishes without needing a single swap. The name comes from how the largest unsorted value rises toward its correct position with every pass, similar to a bubble floating up.
How Does It Work?
Imagine you have an unsorted list of numbers: [5, 1, 4, 2, 8]
- First Pass:
- (5, 1) → Swap → [1, 5, 4, 2, 8]
- (5, 4) → Swap → [1, 4, 5, 2, 8]
- (5, 2) → Swap → [1, 4, 2, 5, 8]
- (5, 8) → No swap
- Second Pass:
- (1, 4) → No swap
- (4, 2) → Swap → [1, 2, 4, 5, 8]
- (4, 5) → No swap
- Third Pass:
- No swaps needed → List is sorted
The algorithm stops when a complete pass is made without any swaps.
Algorithm Steps
- Start with an unsorted array
- Set a flag to track if any swaps occur
- For each pair of adjacent elements:
- Compare the two elements
- If they are in the wrong order, swap them
- Set the swap flag to true
- Repeat the process until a complete pass is made without any swaps
- The array is now sorted
Time Complexity
- Best Case: Array is already sorted → O(n) (only one pass needed).
- Average Case: Randomly ordered array → O(n²).
- Worst Case: Array is sorted in reverse order → O(n²).
Time Complexity Analysis
Space Complexity
Bubble Sort is an in-place sorting algorithm, meaning it requires only O(1) additional space (for temporary storage during swaps).
Bubble Sort is simple to understand and implement but inefficient for large datasets. It's mainly used for educational purposes to introduce sorting algorithms. In practice, more efficient algorithms like QuickSort or MergeSort are preferred.