Bubble Sort Explanation
How It Works
Bubble Sort works by repeatedly comparing adjacent elements and swapping them if they're in the wrong order. The largest element "bubbles up" to the end of the array in each pass.
Step-by-Step Process
-
First Pass: Compare each pair of adjacent elements
- If the first element is greater than the second, swap them
- Continue until the end of the array
- The largest element is now at the end
-
Subsequent Passes: Repeat the process
- Each pass moves the next largest element to its correct position
- The number of comparisons decreases with each pass
-
Completion: The array is sorted when no swaps are needed
Visual Example
Initial: [5, 3, 8, 4, 2]
Pass 1: [3, 5, 4, 2, 8] // 8 bubbles to the end
Pass 2: [3, 4, 2, 5, 8] // 5 bubbles to position
Pass 3: [3, 2, 4, 5, 8] // 4 bubbles to position
Pass 4: [2, 3, 4, 5, 8] // 3 bubbles to position
Why "Bubble"?
The name comes from how larger elements "bubble" to the top (end) of the array, similar to bubbles rising in water.