Skip to content

Commit 68fbd26

Browse files
⚡️ Speed up method Sorter.sort_class by 113,722%
The optimization replaces a naive O(n²) bubble sort implementation with Python's built-in `arr.sort()` method, which uses Timsort - a highly optimized O(n log n) hybrid stable sorting algorithm. **Key changes:** - Removed the nested loop bubble sort implementation (lines with `for i in range(len(arr))` and `for j in range(len(arr) - 1)`) - Replaced the manual element swapping logic with a single `arr.sort()` call - Maintained in-place sorting behavior and return value **Why this is faster:** 1. **Algorithmic complexity**: Bubble sort is O(n²) while Timsort is O(n log n), providing exponential speedup for larger datasets 2. **Implementation efficiency**: Python's built-in sort is implemented in optimized C code vs. interpreted Python loops 3. **Adaptive behavior**: Timsort performs even better on partially sorted data, explaining the massive speedups on already-sorted test cases **Performance results by test case type:** - **Small lists (≤10 elements)**: 70-216% faster due to reduced function call overhead - **Large sorted/reverse-sorted lists**: 676,311-987,901% faster as Timsort detects patterns and optimizes accordingly - **Large random lists**: 65,882-71,127% faster from the fundamental algorithmic improvement - **Lists with many duplicates**: 96,999-105,372% faster as Timsort handles duplicates efficiently The optimization maintains identical behavior including in-place mutation, return value, and exception handling for incomparable elements.
1 parent 8753e54 commit 68fbd26

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)):
@@ -55,10 +60,5 @@ def sort_static(arr):
5560
@classmethod
5661
@codeflash_trace
5762
def sort_class(cls, arr):
58-
for i in range(len(arr)):
59-
for j in range(len(arr) - 1):
60-
if arr[j] > arr[j + 1]:
61-
temp = arr[j]
62-
arr[j] = arr[j + 1]
63-
arr[j + 1] = temp
63+
arr.sort()
6464
return arr

0 commit comments

Comments
 (0)