Skip to content

Commit 29bf14d

Browse files
⚡️ Speed up method Sorter.sort_static by 107,319%
The optimization replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, delivering a massive **107,319% speedup**. **Key Changes:** - **Algorithm replacement**: Swapped O(n²) bubble sort with Python's built-in Timsort (O(n log n) average case) - **Implementation efficiency**: Python's `.sort()` is implemented in C and highly optimized for real-world data patterns - **Preserved behavior**: Maintains in-place sorting and returns the same list object, preserving the original contract **Why This Works:** The original bubble sort performs nested loops with explicit element comparisons and swaps in Python bytecode. For a 1000-element list, this requires ~500,000 comparisons in the worst case. Python's Timsort leverages: - Native C implementation (orders of magnitude faster than Python loops) - Adaptive algorithms that perform better on partially sorted data - Optimized memory access patterns **Performance by Test Case:** - **Small lists (2-10 elements)**: 60-140% faster due to reduced overhead - **Large sorted lists**: 696,790% faster - Timsort detects already-sorted sequences - **Large reverse-sorted lists**: 1,009,760% faster - Timsort handles this pattern efficiently - **Large random lists**: 70,000%+ faster - O(n log n) vs O(n²) complexity advantage The optimization is particularly effective for larger datasets where the algorithmic complexity difference dominates, while still providing consistent improvements across all test cases.
1 parent 8753e54 commit 29bf14d

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,10 +30,12 @@ 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):
3641
for i in range(len(self.arr)):
@@ -44,12 +49,7 @@ def sorter(self, multiplier):
4449
@staticmethod
4550
@codeflash_trace
4651
def sort_static(arr):
47-
for i in range(len(arr)):
48-
for j in range(len(arr) - 1):
49-
if arr[j] > arr[j + 1]:
50-
temp = arr[j]
51-
arr[j] = arr[j + 1]
52-
arr[j + 1] = temp
52+
arr.sort()
5353
return arr
5454

5555
@classmethod

0 commit comments

Comments
 (0)