Skip to content

Commit 438a36a

Browse files
⚡️ Speed up function sorter by 109,180%
The optimization replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, delivering dramatic performance improvements. **Key changes:** - **Eliminated nested loops**: The original O(N²) bubble sort algorithm with nested for loops is replaced by a single `arr.sort()` call - **Leveraged Timsort**: Python's built-in sort uses the highly optimized Timsort algorithm with O(N log N) complexity - **Removed manual swapping**: The three-line element swapping logic is eliminated entirely **Why this creates massive speedup:** - **Algorithmic complexity**: Bubble sort performs ~N²/2 comparisons and swaps, while Timsort performs ~N log N operations - **Native implementation**: `arr.sort()` is implemented in C and highly optimized, versus interpreted Python loops - **Adaptive sorting**: Timsort performs exceptionally well on partially sorted data, explaining the 50,000%+ speedups on large sorted/reverse-sorted lists **Test case performance patterns:** - **Small lists (≤10 elements)**: 15-46% speedup due to reduced Python interpreter overhead - **Large sorted lists**: 50,000%+ speedup as Timsort recognizes existing order - **Large random lists**: 40,000%+ speedup from superior algorithmic complexity - **Lists with duplicates**: 45,000%+ speedup as Timsort handles duplicates efficiently The optimization maintains identical functionality (in-place sorting, return value, print statements) while transforming an academic O(N²) algorithm into production-ready O(N log N) performance.
1 parent ae3c7ca commit 438a36a

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)