Commit 19be13e
authored
Optimize sorter
The optimized code achieves a **79% speedup** through three key algorithmic improvements to the bubble sort:
**1. Reduced Inner Loop Range**: Instead of always iterating `range(len(arr) - 1)`, the optimized version uses `range(n - i - 1)`. This leverages bubble sort's property that after each pass, the largest elements settle at the end, so we don't need to check already-sorted positions.
**2. Early Exit Optimization**: The `swapped` flag tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and we can exit early via `break`. This is especially powerful for already-sorted or nearly-sorted data.
**3. Direct Tuple Swap**: Replaces the traditional 3-line swap using a temporary variable with Python's tuple unpacking: `arr[j], arr[j + 1] = arr[j + 1], arr[j]`. This eliminates one variable assignment per swap.
**Performance Impact by Test Case**:
- **Already sorted data**: Massive gains (37,680% faster for 1000 elements) due to early exit after first pass
- **Nearly sorted data**: Exceptional performance (27,580% faster) as only a few passes are needed
- **All equal elements**: Huge improvement (38,346% faster) with immediate early exit
- **Random/reverse sorted data**: Moderate gains (50-70% faster) from reduced inner loop iterations
- **Small arrays**: Minimal improvement (1-11%) as overhead dominates
The line profiler shows the optimized version performs significantly fewer iterations in the inner loop (43.6M vs 49.8M hits), demonstrating the effectiveness of the reduced range optimization.1 parent 76a923f commit 19be13e
1 file changed
+12
-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 | + | |
| 14 | + | |
| 15 | + | |
9 | 16 | | |
10 | 17 | | |
0 commit comments