Skip to content

Commit 6e7cec5

Browse files
⚡️ Speed up function sorter by 88%
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.
1 parent 7566a6f commit 6e7cec5

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

codeflash/bubble_sort.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from typing import List, Union
2+
3+
4+
def sorter(arr: Union[List[int], List[float]]) -> Union[List[int], List[float]]:
5+
for i in range(len(arr)):
6+
swapped = False
7+
for j in range(len(arr) - i - 1):
8+
if arr[j] > arr[j + 1]:
9+
temp = arr[j]
10+
arr[j] = arr[j + 1]
11+
arr[j + 1] = temp
12+
swapped = True
13+
if not swapped:
14+
break
15+
return arr

0 commit comments

Comments
 (0)