Skip to content

Commit 73eedd0

Browse files
⚡️ Speed up function sorter by 195,917%
The optimization replaces the manual bubble sort implementation with Python's built-in `list.sort()` method, resulting in a **195,916% speedup**. **Key Changes:** - **Algorithm replacement**: The nested loops performing O(n²) bubble sort comparisons and swaps are replaced with a single `arr.sort()` call - **Timsort advantage**: Python's built-in sort uses Timsort, a highly optimized hybrid sorting algorithm implemented in C that runs in O(n log n) time with excellent performance on real-world data patterns **Why This Creates Massive Speedup:** - **Complexity reduction**: From O(n²) bubble sort to O(n log n) Timsort - **C implementation**: Built-in sort is implemented in optimized C code rather than interpreted Python - **Elimination of Python overhead**: No more 32+ million Python bytecode operations for comparisons, assignments, and array accesses visible in the line profiler **Test Case Performance Patterns:** - **Small lists (≤10 elements)**: 13-61% speedup due to reduced Python overhead - **Large lists (1000 elements)**: 19,000-107,000% speedup where the O(n²) vs O(n log n) complexity difference dominates - **Already sorted lists**: Timsort's adaptive nature provides exceptional performance on pre-sorted data - **Lists with duplicates**: Timsort handles duplicate-heavy datasets very efficiently The optimization maintains identical behavior (in-place sorting, same return value) while leveraging Python's most optimized sorting implementation.
1 parent 8753e54 commit 73eedd0

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)