Commit 6e7cec5
authored
⚡️ Speed up function
The optimized code implements two key bubble sort optimizations that significantly reduce unnecessary work:
**1. Reduced Inner Loop Range**: Changed `range(len(arr) - 1)` to `range(len(arr) - i - 1)`. This eliminates redundant comparisons since bubble sort guarantees that after each outer loop iteration `i`, the largest `i+1` elements are already in their correct positions at the end of the array.
**2. Early Exit with Swap Detection**: Added a `swapped` flag that tracks whether any swaps occurred during an inner loop pass. If no swaps happen, the array is already sorted and the algorithm can terminate early via `break`.
**Performance Impact**: The line profiler shows the inner loop executed ~12.25M times in the original vs ~4.88M times in the optimized version - a 60% reduction in iterations. This translates to an 88% speedup (446ms → 237ms).
**Best Case Scenarios**: The optimizations are particularly effective for:
- **Already sorted arrays** (like `test_sorter_large_sorted`): Early exit after first pass
- **Nearly sorted arrays**: Minimal swaps trigger early termination
- **Large arrays**: The O(n²) → O(n) improvement for best cases becomes more pronounced
The swapping logic and in-place mutation behavior remain identical, ensuring full correctness while dramatically improving performance for common real-world scenarios where data is often partially sorted.sorter by 88%1 parent 7566a6f commit 6e7cec5
1 file changed
+15
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
0 commit comments