Skip to content

Commit b8aef66

Browse files
⚡️ Speed up function sorter by 101%
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.
1 parent 8753e54 commit b8aef66

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

code_to_optimize/bubble_sort_codeflash_trace.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
from codeflash.benchmarking.codeflash_trace import codeflash_trace
2+
3+
24
@codeflash_trace
35
def sorter(arr):
46
for i in range(len(arr)):
5-
for j in range(len(arr) - 1):
7+
swapped = False
8+
for j in range(len(arr) - 1 - i):
69
if arr[j] > arr[j + 1]:
7-
temp = arr[j]
8-
arr[j] = arr[j + 1]
9-
arr[j + 1] = temp
10+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
11+
swapped = True
12+
if not swapped:
13+
break
1014
return arr
1115

16+
1217
@codeflash_trace
1318
def recursive_bubble_sort(arr, n=None):
1419
# Initialize n if not provided
@@ -27,10 +32,12 @@ def recursive_bubble_sort(arr, n=None):
2732
# Recursively sort the remaining n-1 elements
2833
return recursive_bubble_sort(arr, n - 1)
2934

35+
3036
class Sorter:
3137
@codeflash_trace
3238
def __init__(self, arr):
3339
self.arr = arr
40+
3441
@codeflash_trace
3542
def sorter(self, multiplier):
3643
for i in range(len(self.arr)):

0 commit comments

Comments
 (0)