Skip to content

Commit d231a67

Browse files
⚡️ Speed up function sorter by 175,390%
The optimization replaces a manual O(n²) bubble sort implementation with Python's built-in `arr.sort()` method, which uses the highly optimized Timsort algorithm (O(n log n)). **Key changes:** - **Eliminated nested loops**: The original code had nested `for` loops that compared every element with every other element, resulting in ~113 million operations for larger inputs - **Replaced with `arr.sort()`**: Uses Python's native sorting implementation written in C, which is dramatically faster - **Preserved all behavior**: The function still sorts in-place, prints the same messages, and returns the sorted array **Why this leads to massive speedup:** - **Algorithmic complexity**: Bubble sort is O(n²) while Timsort is O(n log n) - for 1000 elements, that's ~1,000,000 vs ~10,000 operations - **Implementation efficiency**: Python's built-in sort is implemented in optimized C code rather than interpreted Python loops - **Reduced function calls**: Eliminates millions of array indexing operations, comparisons, and assignments **Performance gains by test case type:** - **Small lists (≤10 elements)**: 20-90% faster due to reduced overhead - **Medium lists (100 elements)**: 2,000-4,000% faster as algorithmic advantages emerge - **Large lists (1000 elements)**: 9,000-100,000% faster where O(n²) vs O(n log n) difference is most pronounced - **Already sorted lists**: Particularly dramatic gains since bubble sort still does O(n²) work while Timsort optimizes for sorted data The line profiler shows the original code spent 32% of time in comparisons and 36% in swapping operations across millions of iterations, all replaced by a single efficient sort call.
1 parent 741bdd2 commit d231a67

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() # In-place, preserves behavioral side effects and mutations
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)