Derive the exact key comparison formulas for Bubble Sort, Selection Sort, and Insertion Sort in best, worst, and average cases.
The three elementary sorting algorithms exhibit distinct analytical comparison profiles governed by their inner loop termination invariants:
1. Selection Sort:
- Comparison Mechanism: In pass i (from 0 to n − 2), the algorithm scans the remaining unsorted suffix A[i .. n-1] to locate the minimum key. The inner loop always executes exactly n − 1 − i comparisons, independent of the values in the array.
- Total Comparisons: C(n) = ∑_{i=0}^{n-2} (n − 1 − i) = (n − 1) + (n − 2) + ... + 1 = n(n − 1)/2.
- Best, Worst, and Average Cases: All identically Θ(n²). Selection Sort is completely non-adaptive with respect to comparisons.
2. Bubble Sort:
- Comparison Mechanism: Compares adjacent pairs A[j] and A[j+1] for j from 0 to n − 2 − i.
- Worst-Case (Reverse-Sorted): Without early exit or on reversed keys, executes ∑_{i=0}^{n-2} (n − 1 − i) = n(n − 1)/2 comparisons = Θ(n²).
- Best-Case (Already Sorted with Early-Exit Flag): If a boolean swapped flag tracks whether any exchange occurred in a pass, the first pass verifies sortedness with n − 1 comparisons and immediately terminates: C_best(n) = n − 1 = Θ(n).
- Average-Case: Θ(n²) comparisons.
3. Insertion Sort:
- Comparison Mechanism: Inserts A[i] into the sorted prefix A[0 .. i-1] by shifting larger elements right. In pass i, it performs between 1 and i comparisons.
- Best-Case (Already Sorted): Exactly 1 comparison per element: C_best(n) = n − 1 = Θ(n).
- Worst-Case (Reverse-Sorted): Requires i comparisons per element: C_worst(n) = ∑_{i=1}^{n-1} i = n(n − 1)/2 = Θ(n²).
- Average-Case (Random Permutation): Each element is expected to move halfway through the sorted prefix: E[C_i] ≈ i/2, yielding C_avg(n) = ∑_{i=1}^{n-1} i/2 = n(n − 1)/4 = Θ(n²).