The algorithm operates on the principle of Passes and Iterations. In each pass, the algorithm traverses the unsorted portion of the array, comparing every pair of adjacent elements.
The Bubbling Invariant states that after the -th pass, the largest elements of the array are guaranteed to be in their final, sorted positions at the end of the array. This reduces the search space for each subsequent pass.
The total number of comparisons in the worst-case scenario follows an arithmetic progression: . This results in a mathematical complexity of , which simplifies to .
| Feature | Bubble Sort | Selection Sort | Insertion Sort |
|---|---|---|---|
| Mechanism | Adjacent Swaps | Finding Minimum | Shifting Elements |
| Stability | Stable | Unstable | Stable |
| Best Case | (Optimized) | ||
| Worst Case |
Unlike Selection Sort, which performs exactly one swap per pass, Bubble Sort may perform multiple swaps per pass. However, Bubble Sort can detect a sorted list early, whereas Selection Sort always runs to completion.
Compared to Insertion Sort, Bubble Sort generally performs more write operations (swaps) because it moves elements one step at a time, while Insertion Sort shifts elements more efficiently within a single pass.
Identify the State: If an exam question asks for the state of an array after passes, look at the last elements. They must be the largest elements in sorted order.
Complexity Analysis: Always specify if you are discussing the standard or optimized version. The standard version is always , while the optimized version achieves for a pre-sorted list.
Check for Stability: Remember that Bubble Sort is stable because it only swaps elements if they are strictly greater (or smaller). If elements are equal, no swap occurs, preserving their relative order.
Boundary Conditions: Watch for off-by-one errors in loop limits. The inner loop should typically run from to to stay within array bounds and avoid redundant comparisons.