Skip to content

Commit 10a2794

Browse files
⚡️ Speed up function sorter by 172,818%
The optimization replaces a manual bubble sort implementation with Python's built-in `list.sort()` method, resulting in a dramatic performance improvement. **Key Changes:** - **Algorithm replacement**: Eliminated the nested loops implementing bubble sort (O(n²) time complexity) and replaced with a single `arr.sort()` call - **Leverages Timsort**: Python's built-in sort uses Timsort, an adaptive hybrid sorting algorithm with O(n log n) average case complexity - **Reduced operation count**: The original code performed up to 114 million operations for large inputs, while the optimized version performs the sort in a single highly-optimized C implementation call **Why This Leads to Speedup:** - **Time complexity improvement**: Bubble sort's O(n²) becomes Timsort's O(n log n), providing exponential improvement for larger datasets - **Implementation efficiency**: Python's built-in sort is implemented in C and heavily optimized, versus interpreted Python loops with element swapping - **Adaptive optimization**: Timsort performs exceptionally well on partially sorted data, already-sorted data, and reverse-sorted data through intelligent run detection **Test Case Performance Patterns:** - **Small lists (≤10 elements)**: 30-70% faster due to reduced overhead - **Large sorted/reverse-sorted lists**: 60,000-100,000% faster as Timsort recognizes existing order patterns - **Large random lists**: 30,000-50,000% faster from O(n²) to O(n log n) complexity reduction - **Lists with duplicates**: Significant speedup as Timsort handles equal elements efficiently The optimization maintains identical behavior including in-place sorting and return value while achieving massive performance gains, especially pronounced on larger datasets where the algorithmic complexity difference dominates.
1 parent 388890c commit 10a2794

File tree

1 file changed

+1
-6
lines changed

1 file changed

+1
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
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):
5-
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
3+
arr.sort()
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)