Skip to content

Commit 9ffbf72

Browse files
⚡️ Speed up function sorter by 139,489%
The optimized code replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, achieving a **139,488% speedup** (from 3.65 seconds to 2.61 milliseconds). **Key Optimization:** - **Replaced O(n²) bubble sort with Timsort**: The original code used nested loops with O(n²) time complexity, performing up to 114 million iterations and 53 million swaps for larger inputs. The optimized version uses Python's highly optimized `sort()` method, which implements Timsort - a hybrid stable sorting algorithm with O(n log n) average case performance. **Why This Works:** - **Algorithm complexity**: Bubble sort's quadratic time complexity becomes prohibitively expensive as input size grows, while Timsort scales much better - **Native C implementation**: Python's `sort()` is implemented in C and heavily optimized for real-world data patterns - **Adaptive performance**: Timsort performs exceptionally well on already sorted or partially sorted data, explaining the massive speedups on ordered inputs (55,692% faster on sorted lists, 91,722% on reverse-sorted) **Test Case Performance:** - **Small lists (≤10 elements)**: Modest 8-36% improvements due to overhead being comparable - **Large lists (1000 elements)**: Dramatic improvements of 10,000-90,000% faster, demonstrating the quadratic vs linearithmic complexity difference - **Best for**: Large datasets, partially sorted data, and any production sorting needs where performance matters The optimization maintains identical functionality, preserving in-place sorting behavior and all print statements.
1 parent bd320ee commit 9ffbf72

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
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+
# Use Python's built-in sort for significantly better performance
4+
arr.sort()
95
print(f"result: {arr}")
106
return arr

0 commit comments

Comments
 (0)