Skip to content

Commit b389fa3

Browse files
⚡️ Speed up method Sorter.sorter by 205,046%
The optimization replaces a manual bubble sort implementation with Python's built-in `sort()` method, delivering massive performance gains. **What was optimized:** - Replaced the nested O(n²) bubble sort loops with `self.arr.sort()`, which uses Timsort (O(n log n) average case) - Eliminated manual element swapping and redundant array accesses - Preserved exact behavior: sorts `self.arr` in-place and returns `self.arr * multiplier` **Why this is dramatically faster:** 1. **Algorithmic complexity**: Timsort is O(n log n) vs bubble sort's O(n²), making it exponentially faster for larger inputs 2. **Native implementation**: Python's `sort()` is implemented in highly optimized C code 3. **Reduced overhead**: Eliminates Python loop overhead and multiple array index operations per comparison **Test case performance patterns:** - **Small arrays (2-4 elements)**: 70-160% speedup due to reduced Python overhead - **Large arrays (100-1000 elements)**: 15,000x to 1,000,000x+ speedup due to algorithmic efficiency - **Already sorted data**: Massive gains since Timsort has O(n) best-case performance vs bubble sort's O(n²) regardless of input order - **Reverse sorted data**: Most dramatic improvements (1,000,000x+) as this is bubble sort's worst case The optimization maintains identical sorting behavior and return value semantics while delivering the most significant performance improvement for larger datasets where the O(n²) vs O(n log n) complexity difference dominates.
1 parent 8753e54 commit b389fa3

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

code_to_optimize/bubble_sort_codeflash_trace.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
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)):
@@ -9,6 +11,7 @@ def sorter(arr):
911
arr[j + 1] = temp
1012
return arr
1113

14+
1215
@codeflash_trace
1316
def recursive_bubble_sort(arr, n=None):
1417
# Initialize n if not provided
@@ -27,18 +30,15 @@ def recursive_bubble_sort(arr, n=None):
2730
# Recursively sort the remaining n-1 elements
2831
return recursive_bubble_sort(arr, n - 1)
2932

33+
3034
class Sorter:
3135
@codeflash_trace
3236
def __init__(self, arr):
3337
self.arr = arr
38+
3439
@codeflash_trace
3540
def sorter(self, multiplier):
36-
for i in range(len(self.arr)):
37-
for j in range(len(self.arr) - 1):
38-
if self.arr[j] > self.arr[j + 1]:
39-
temp = self.arr[j]
40-
self.arr[j] = self.arr[j + 1]
41-
self.arr[j + 1] = temp
41+
self.arr.sort()
4242
return self.arr * multiplier
4343

4444
@staticmethod

0 commit comments

Comments
 (0)