Commit 6f7004e
authored
Optimize sorter
The optimized bubble sort implements two key algorithmic improvements that significantly reduce unnecessary operations:
**1. Early Exit Optimization**: The code adds a `swapped` flag to detect when the array becomes sorted during any pass. If no swaps occur in a complete pass, the array is already sorted and the algorithm terminates early. This is especially powerful for already-sorted or nearly-sorted data, as seen in the test results where sorted lists show dramatic speedups (99924% faster for large sorted lists).
**2. Reduced Inner Loop Range**: The inner loop range changes from `range(len(arr) - 1)` to `range(len(arr) - 1 - i)`. After each outer loop iteration, the largest remaining element "bubbles up" to its correct position at the end, so there's no need to re-examine those already-sorted tail elements.
**Performance Impact**: The line profiler shows the inner loop executes ~4.98M times vs ~14M times in the original (64% reduction). While the swapping operations remain identical (same number of swaps needed), the algorithm eliminates millions of redundant comparisons. The speedup is most pronounced on:
- Already sorted data: 99924% faster (exits after first pass)
- Lists with many duplicates: 7645% faster (becomes sorted quickly)
- Mixed random data: 63-76% faster (fewer total comparisons)
These optimizations maintain bubble sort's O(n²) worst-case complexity but achieve O(n) best-case performance when data is already sorted, making it much more practical for real-world scenarios where input data may have some existing order.1 parent e0a80e9 commit 6f7004e
1 file changed
+5
-1
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 | | |
7 | 8 | | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
8 | 12 | | |
0 commit comments