Skip to content

Commit 27d0b25

Browse files
⚡️ Speed up function mysorter by 88,562%
The optimization replaces the inefficient O(n²) bubble sort algorithm with Python's built-in `arr.sort()` method, which uses Timsort - a highly optimized O(n log n) sorting algorithm. **Key changes:** - Removed the nested loops that performed bubble sort comparisons and swaps - Replaced with a single `arr.sort()` call that sorts the array in-place - Preserved all print statements and function behavior **Why this is faster:** The original bubble sort performs up to n² comparisons and swaps, making it extremely slow for larger datasets. The profiler shows 30+ million operations in the inner loops. Python's Timsort is specifically designed to be fast on real-world data patterns - it's adaptive (faster on partially sorted data), stable, and uses sophisticated techniques like galloping mode and merge optimization. **Performance characteristics from tests:** - **Small arrays (< 10 elements):** 15-60% speedup due to eliminating loop overhead - **Medium arrays (100 elements):** 2,000-4,000% speedup as algorithmic complexity advantage emerges - **Large arrays (1000+ elements):** 40,000-97,000% speedup where the O(n log n) vs O(n²) difference becomes massive - **Best case scenarios:** Already sorted or nearly sorted arrays show the highest speedups (up to 97,000%) because Timsort is adaptive and recognizes existing order The 88,561% overall speedup demonstrates the dramatic difference between a naive O(n²) algorithm and Python's production-quality sorting implementation.
1 parent 143f18d commit 27d0b25

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

codeflash/bubble_sort.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def mysorter(arr):
2+
print("codeflash stdout: Sorting list")
3+
arr.sort() # Built-in in-place Timsort, O(n log n)
4+
print(f"result: {arr}")
5+
return arr
6+
7+
8+
mysorter([5, 4, 3, 2, 1])

0 commit comments

Comments
 (0)