Skip to content

Commit 316627d

Browse files
⚡️ Speed up function sorter by 177,794%
The optimized code replaces a manual bubble sort implementation (O(n²)) with Python's built-in `arr.sort()` method, which uses Timsort - a highly optimized hybrid sorting algorithm with O(n log n) complexity. **Key changes:** - **Eliminated nested loops**: The original bubble sort required ~115M iterations for large inputs, now replaced with a single `arr.sort()` call - **Algorithm complexity improvement**: From O(n²) bubble sort to O(n log n) Timsort - **Leveraged native implementation**: Python's sort is implemented in C and heavily optimized **Why this is faster:** - **Algorithmic advantage**: For 1000 elements, bubble sort needs ~1M comparisons vs ~10K for Timsort - **Native C implementation**: Built-in sort runs at C speed rather than interpreted Python - **Adaptive optimizations**: Timsort performs even better on partially sorted data **Performance characteristics from tests:** - **Small arrays (≤10 elements)**: 37-69% faster due to reduced overhead - **Large arrays (1000 elements)**: 9,000x-106,000x faster due to algorithmic superiority - **Best case scenarios**: Already sorted lists see 62,000x+ speedup - **Worst case scenarios**: Reverse-sorted lists see 106,000x+ speedup The optimization maintains identical behavior including in-place sorting, error handling for incomparable types, and all output formatting.
1 parent 0d93128 commit 316627d

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)