Commit 334665a
authored
Optimize sorter
The optimized code implements two key bubble sort optimizations that significantly improve performance:
**1. Early Exit with Swap Detection**: The algorithm tracks whether any swaps occurred during a pass using a `swapped` flag. If no swaps happen, the array is fully sorted and the algorithm exits early. This provides massive speedups for already-sorted or nearly-sorted data (35,765% faster for sorted arrays, 36,109% faster for arrays with all duplicates).
**2. Reduced Comparison Range**: Each pass reduces the inner loop range by `i` elements (`range(n - i - 1)` vs `range(len(arr) - 1)`), since the last `i` elements are guaranteed to be in their final sorted positions after `i` passes. This eliminates unnecessary comparisons.
**3. Tuple Unpacking for Swaps**: Replaces the three-line temporary variable swap with Python's tuple unpacking (`arr[j], arr[j + 1] = arr[j + 1], arr[j]`), which is more efficient and eliminates one variable assignment per swap.
The line profiler shows the optimized version performs ~53M inner loop iterations vs ~110M in the original (52% reduction), directly correlating to the 81% runtime improvement. The optimizations are particularly effective for:
- Already sorted data (early exit after first pass)
- Data with many duplicates (early exit when no more swaps needed)
- Large datasets (reduced comparisons compound the savings)
Even for worst-case scenarios like reverse-sorted arrays, the reduced comparison range still provides 54-74% speedups.1 parent 0d43f6d commit 334665a
1 file changed
+10
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
5 | 9 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
9 | 14 | | |
10 | 15 | | |
0 commit comments