Skip to content

Commit 19be13e

Browse files
Optimize sorter
The optimized code achieves a **79% speedup** through three key algorithmic improvements to the bubble sort: **1. Reduced Inner Loop Range**: Instead of always iterating `range(len(arr) - 1)`, the optimized version uses `range(n - i - 1)`. This leverages bubble sort's property that after each pass, the largest elements settle at the end, so we don't need to check already-sorted positions. **2. Early Exit Optimization**: The `swapped` flag tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and we can exit early via `break`. This is especially powerful for already-sorted or nearly-sorted data. **3. Direct Tuple Swap**: Replaces the traditional 3-line swap using a temporary variable with Python's tuple unpacking: `arr[j], arr[j + 1] = arr[j + 1], arr[j]`. This eliminates one variable assignment per swap. **Performance Impact by Test Case**: - **Already sorted data**: Massive gains (37,680% faster for 1000 elements) due to early exit after first pass - **Nearly sorted data**: Exceptional performance (27,580% faster) as only a few passes are needed - **All equal elements**: Huge improvement (38,346% faster) with immediate early exit - **Random/reverse sorted data**: Moderate gains (50-70% faster) from reduced inner loop iterations - **Small arrays**: Minimal improvement (1-11%) as overhead dominates The line profiler shows the optimized version performs significantly fewer iterations in the inner loop (43.6M vs 49.8M hits), demonstrating the effectiveness of the reduced range optimization.
1 parent 76a923f commit 19be13e

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
3-
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
3+
n = len(arr)
4+
# Optimized bubble sort: on each pass, the largest elements settle at the end.
5+
for i in range(n):
6+
swapped = False
7+
# Reduce inner loop range for already-sorted tail
8+
for j in range(n - i - 1):
59
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
10+
# Swap elements directly (no temp variable needed)
11+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
12+
swapped = True
13+
# Early exit if no swaps, array is already sorted
14+
if not swapped:
15+
break
916
print(f"result: {arr}")
1017
return arr

0 commit comments

Comments
 (0)