Skip to content

Commit 16e1a79

Browse files
⚡️ Speed up function sorter by 104,077%
The optimization replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, delivering a massive **104,077% speedup**. **What changed:** - Removed the nested loops that implement bubble sort (O(n²) complexity) - Replaced with a single call to `arr.sort()` which uses Timsort (O(n log n) complexity) **Why this is dramatically faster:** The original bubble sort performs ~62 million comparisons and ~27 million swaps for larger datasets, as shown in the line profiler. Each comparison (`arr[j] > arr[j + 1]`) and swap operation takes significant time when repeated millions of times. Python's built-in `sort()` uses Timsort, a highly optimized hybrid stable sorting algorithm that: - Has O(n log n) time complexity vs O(n²) for bubble sort - Is implemented in C, making individual operations much faster - Uses adaptive techniques that perform better on partially sorted data **Performance gains by test case type:** - **Small lists (≤10 elements)**: 15-40% faster - modest gains since overhead dominates - **Medium lists (~100 elements)**: 1,000-2,000% faster - algorithm efficiency starts showing - **Large lists (1000+ elements)**: 10,000-90,000% faster - massive gains where O(n²) vs O(n log n) difference is most pronounced - **Best case scenarios**: Already sorted or reverse sorted large lists show the highest speedups (55,000-92,000%) due to Timsort's adaptive nature The optimization maintains identical behavior including in-place sorting and all print statements.
1 parent ae3c7ca commit 16e1a79

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

codeflash/bubble_sort.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def sorter(arr):
2+
print("codeflash stdout: Sorting list")
3+
arr.sort()
4+
print(f"result: {arr}")
5+
return arr

0 commit comments

Comments
 (0)