Commit 35e8fee
authored
Optimize sorter
The optimized code implements three key improvements to the bubble sort algorithm:
**1. Reduced comparisons per pass**: Changed `range(len(arr) - 1)` to `range(n - 1 - i)`. This eliminates redundant comparisons since bubble sort guarantees the largest `i` elements are already in their final positions after `i` passes. This reduces the inner loop iterations from ~116M to ~56M hits.
**2. Early termination with swap detection**: Added a `swapped` flag that tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and the algorithm can exit early. This is particularly effective for already-sorted or nearly-sorted data, where the algorithm can terminate in O(n) time instead of O(n²).
**3. Optimized swap operation**: Replaced the three-line temporary variable swap with Python's tuple unpacking (`arr[j], arr[j + 1] = arr[j + 1], arr[j]`). This is more efficient as it's implemented at the bytecode level.
**Performance gains by test case type**:
- **Already sorted lists**: Massive improvements (17,000%+ faster) due to early termination after one pass
- **Lists with identical elements**: Significant speedup (18,000%+ faster) as no swaps are needed
- **Random/unsorted lists**: Moderate improvements (50-75% faster) from reduced comparisons
- **Small lists**: Minor improvements (5-15% faster) as optimizations have less impact
The optimized version maintains the same O(n²) worst-case complexity but achieves O(n) best-case performance for sorted inputs, explaining the dramatic speedup in many test scenarios.1 parent bb35a60 commit 35e8fee
1 file changed
+8
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
5 | 7 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
9 | 12 | | |
10 | 13 | | |
0 commit comments