Skip to content

Commit 5c43250

Browse files
Optimize sorter
The optimized bubble sort implements two key algorithmic improvements that significantly reduce unnecessary operations: **1. Reduced Inner Loop Range**: The inner loop now uses `range(len(arr) - 1 - i)` instead of `range(len(arr) - 1)`. This optimization recognizes that after each outer loop iteration, the largest remaining element has "bubbled" to its correct position at the end. By reducing the range by `i` elements each pass, we avoid redundant comparisons of already-sorted elements, cutting total iterations from ~115M to ~55M. **2. Early Termination with Swap Detection**: The algorithm tracks whether any swaps occurred during a pass using the `swapped` flag. If no swaps happen, the array is fully sorted and the algorithm exits early via `break`. This provides dramatic speedups for already-sorted or nearly-sorted inputs - as seen in the test results where sorted arrays show 17,000%+ improvements (16.5ms → 94.2μs). **3. Tuple Swap Optimization**: Replaced the three-line temporary variable swap with Python's tuple unpacking `arr[j], arr[j + 1] = arr[j + 1], arr[j]`, which is more efficient at the bytecode level. These optimizations are most effective for: - **Already sorted data**: Massive speedups (17,000%+) due to early termination after first pass - **Partially sorted data**: Significant improvements (60-70%) from reduced iterations and early exits - **Large datasets**: Better performance scaling as unnecessary work is eliminated - **Lists with many duplicates**: Good improvements (69%+) as duplicate regions sort quickly The optimizations maintain identical behavior while reducing algorithmic complexity from O(n²) comparisons in all cases to O(n) for best-case scenarios.
1 parent 4b1a2f3 commit 5c43250

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
33
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
4+
swapped = False
5+
for j in range(len(arr) - 1 - i):
56
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
7+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
8+
swapped = True
9+
if not swapped:
10+
break
911
print(f"result: {arr}")
1012
return arr

0 commit comments

Comments
 (0)