ABSTRACT
Bubble Sort is a simple, comparison-based sorting algorithm. It works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The algorithm gets its name because the largest elements “bubble up” to their correct positions at the end of the list.
The Strategy
For a list :
- Compare & Swap: Compare and . If , swap them.
- Pass Completion: Continue this all the way to the end of the current unsorted range.
- Result: The largest element in that range is now at the final position.
- Reduce Range: Repeat the process, reducing the “end” of the list by one each time until no more swaps are needed.

Optimization: Early Exit
Standard Bubble Sort is “blind”—it continues iterating even if the list becomes sorted mid-way. By adding a boolean flag (e.g., swapped), we can terminate the algorithm early.
- Logic: If a full pass is completed without a single swap occurring, the list is guaranteed to be sorted.
- Impact: This improves the Best Case time complexity significantly.

Proof of Correctness (Sketch)
- Invariant: After passes, the largest elements are correctly sorted at the end of the list.
- Base Case: After 1 pass, the largest element has “bubbled” to position .
- Inductive Step: If the largest elements are in place, the pass will find the largest element in the remaining unsorted elements and move it to position .
Time Analysis
On a list of length :
1. Number of Swaps
- Best Case: (The list is already sorted).
- Worst Case: (The list is in reverse order).
2. Number of Comparisons
- Best Case (with Early Exit): (Only one pass is needed to verify it is sorted).
- Worst Case: (Requires all passes).
NOTE
In Big-O notation, Bubble Sort is in the worst and average cases. Because it only swaps adjacent elements, it is generally less efficient than Selection Sort (Min Sort) or Insertion Sort.
Pros and Cons
| Strengths | Weaknesses |
|---|---|
| Stable: Maintains relative order of equal elements. | Very slow () for large datasets. |
| In-place: Requires extra memory. | Performs many more swaps than Selection Sort. |
| Simple: Extremely easy to implement. |
Related Notes
- Sorting Index — Compare Selection Sort to other algorithms.
- Selection Sort (Min Sort) — A similar sort that minimizes swaps.
- Asymptotic Notation — Understanding why scales poorly.