Commit 5c43250
authored
Optimize sorter
The optimized bubble sort implements two key algorithmic improvements that significantly reduce unnecessary operations:
**1. Reduced Inner Loop Range**: The inner loop now uses `range(len(arr) - 1 - i)` instead of `range(len(arr) - 1)`. This optimization recognizes that after each outer loop iteration, the largest remaining element has "bubbled" to its correct position at the end. By reducing the range by `i` elements each pass, we avoid redundant comparisons of already-sorted elements, cutting total iterations from ~115M to ~55M.
**2. Early Termination with Swap Detection**: The algorithm tracks whether any swaps occurred during a pass using the `swapped` flag. If no swaps happen, the array is fully sorted and the algorithm exits early via `break`. This provides dramatic speedups for already-sorted or nearly-sorted inputs - as seen in the test results where sorted arrays show 17,000%+ improvements (16.5ms → 94.2μs).
**3. Tuple Swap Optimization**: Replaced 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 at the bytecode level.
These optimizations are most effective for:
- **Already sorted data**: Massive speedups (17,000%+) due to early termination after first pass
- **Partially sorted data**: Significant improvements (60-70%) from reduced iterations and early exits
- **Large datasets**: Better performance scaling as unnecessary work is eliminated
- **Lists with many duplicates**: Good improvements (69%+) as duplicate regions sort quickly
The optimizations maintain identical behavior while reducing algorithmic complexity from O(n²) comparisons in all cases to O(n) for best-case scenarios.1 parent 4b1a2f3 commit 5c43250
1 file changed
+6
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
| 4 | + | |
| 5 | + | |
5 | 6 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
9 | 11 | | |
10 | 12 | | |
0 commit comments