Skip to content

Commit ef11217

Browse files
⚡️ Speed up function sorter by 197,541%
The optimization replaces the O(N²) bubble sort implementation with Python's built-in `arr.sort()`, which uses the highly optimized Timsort algorithm (O(N log N)). **Key Changes:** - Removed the nested loop structure that performed 83+ million operations for large inputs - Replaced manual element swapping with Python's native sorting implementation - Eliminated redundant `len(arr) - 1` calculations in the inner loop **Why This Creates Massive Speedup:** The original bubble sort has quadratic time complexity, making ~N²/2 comparisons and up to N²/2 swaps. Python's Timsort is a hybrid stable sorting algorithm that: - Runs in O(N log N) worst case, O(N) best case for already-sorted data - Uses highly optimized C implementation - Employs intelligent techniques like run detection and galloping mode **Performance by Test Case Type:** - **Small lists (≤10 elements):** 20-60% faster - overhead reduction from eliminating nested loops - **Large sorted lists:** 60,000%+ faster - Timsort detects existing order and runs in near-linear time - **Large random/reverse sorted lists:** 40,000-98,000%+ faster - demonstrates the O(N log N) vs O(N²) algorithmic advantage - **Lists with duplicates:** 37,000-84,000%+ faster - Timsort handles duplicates efficiently without unnecessary comparisons The line profiler shows the original code spent 26.5% of time just in the inner loop range calculation and 30.6% in comparisons, totaling over 83 million operations. The optimized version eliminates this entirely with a single efficient sort call.
1 parent 143f18d commit ef11217

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() # Use Python's built-in sort for much faster performance
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)