Commit 86b51a8
authored
⚡️ Speed up function
The optimized code implements two key bubble sort optimizations that dramatically improve performance:
**1. Early Termination with Swap Detection**
- Added a `swapped` flag that tracks if any swaps occurred during a pass
- If no swaps happen in a complete pass, the array is already sorted and the algorithm breaks early
- This provides massive speedups for already-sorted or nearly-sorted data (97,000%+ faster on sorted arrays)
**2. Reduced Inner Loop Bounds**
- Changed inner loop from `range(len(arr) - 1)` to `range(n - 1 - i)`
- Each outer pass guarantees the largest remaining element "bubbles" to its final position
- Subsequent passes don't need to check already-sorted elements at the end
- Reduces total comparisons from O(n²) to a more efficient O(n²) with better constants
**Performance Analysis:**
- The line profiler shows 61% fewer total hits (5.5M vs 14M) in the inner loop comparison
- Early termination benefits are most dramatic for sorted/nearly-sorted data (test cases show 57-105,141% speedups)
- Even worst-case scenarios (reverse-sorted arrays) see 30-35% improvements due to reduced loop bounds
- Random data sees consistent 50-70% speedups across different data types
**Why It's Faster:**
- Fewer redundant comparisons by avoiding already-sorted tail elements
- Eliminates unnecessary passes when sorting completes early
- Cache-friendly access patterns remain unchanged while reducing total memory accesses
- The optimizations work particularly well for real-world data that often has some existing order
The optimized version maintains identical behavior and in-place mutation while providing substantial performance gains across all test scenarios.sorter by 81%1 parent 02b4d65 commit 86b51a8
1 file changed
+7
-2
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
4 | 6 | | |
5 | 7 | | |
6 | 8 | | |
7 | 9 | | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
8 | 13 | | |
0 commit comments