Commit b8aef66
authored
⚡️ Speed up function
The optimized bubble sort implements three key performance improvements:
**1. Reduced Inner Loop Range**: The inner loop uses `range(len(arr) - 1 - i)` instead of `range(len(arr) - 1)`. This avoids redundant comparisons since after each outer loop iteration, the largest `i` elements are already in their final sorted positions at the end of the array.
**2. Early Termination**: 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 breaks early. This provides massive speedups for already-sorted or partially-sorted data.
**3. Tuple Swap**: Replaced the 3-line temporary variable swap with Python's tuple assignment `arr[j], arr[j + 1] = arr[j + 1], arr[j]`, which is more efficient at the bytecode level.
**Performance Impact**: The test results show the optimization is particularly effective for:
- **Already sorted lists**: 95,776% faster (55.6ms → 58.0μs) - early termination eliminates all unnecessary passes
- **Lists with duplicates**: 101-131% faster - fewer comparisons needed due to reduced inner loop
- **Partially sorted data**: 79.2% faster for already sorted with duplicates - early termination kicks in quickly
Even worst-case scenarios (reverse sorted) see 58-59% improvement due to the reduced inner loop range, while maintaining the same O(n²) complexity.sorter by 101%1 parent 8753e54 commit b8aef66
1 file changed
+11
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
| 2 | + | |
| 3 | + | |
2 | 4 | | |
3 | 5 | | |
4 | 6 | | |
5 | | - | |
| 7 | + | |
| 8 | + | |
6 | 9 | | |
7 | | - | |
8 | | - | |
9 | | - | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
10 | 14 | | |
11 | 15 | | |
| 16 | + | |
12 | 17 | | |
13 | 18 | | |
14 | 19 | | |
| |||
27 | 32 | | |
28 | 33 | | |
29 | 34 | | |
| 35 | + | |
30 | 36 | | |
31 | 37 | | |
32 | 38 | | |
33 | 39 | | |
| 40 | + | |
34 | 41 | | |
35 | 42 | | |
36 | 43 | | |
| |||
0 commit comments