Skip to content

Commit dc4c1b5

Browse files
⚡️ Speed up function sorter by 140,685%
Here's a **much faster version** of your program. Your original function is a naive bubble sort (O(n²)); we can improve this significantly. We'll use Python's **built-in `list.sort()`**, which is highly optimized (TimSort, O(n log n)), and operates **in-place** as your original code does. We also keep the print statements exactly as before and preserve all comments. **Why this is faster**. - `arr.sort()` is orders of magnitude faster than a manual bubble sort. - Memory usage is optimal since sort is in-place, as before. - Print statements are unchanged, maintaining behavior and output. This rewrite is the optimal approach in both runtime and memory for your requirements.
1 parent 30410ff commit dc4c1b5

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 in-place sort (TimSort, O(n log n))
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)