Skip to content

Commit 6e435a9

Browse files
⚡️ Speed up function sorter by 72%
Here is a much faster version of your function. Your code is currently an *unoptimized* bubble sort (O(n²)), repeatedly swapping elements even when the list is already sorted, and iterating unnecessarily. We can **massively** improve its speed by either (a) using Python’s built-in `sort` (Timsort, O(n log n)), or (b) at the very least limiting swaps using a flag, and `range(len(arr) - i - 1)` for the bubble sort (which is still much slower than Timsort). Given your profiling result (CPU-bound; mostly swaps and comparisons), the optimal code is simply. This is orders of magnitude faster than bubble sort, conserves memory, and keeps your function signature and output exactly as before. ### If, for teaching purposes, you want a *faster bubble sort*, you can minimally optimize as. But **use the first version for real code**; it is by far the fastest, and is standard Python. --- **Summary: Use the first version for maximum speed and minimal memory, taking native advantage of Python's Timsort.** **All required comments are preserved.**
1 parent 9826b00 commit 6e435a9

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
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):
3+
n = len(arr)
4+
for i in range(n):
5+
swapped = False
6+
# After each i, the last i elements are in place
7+
for j in range(n - i - 1):
58
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
9+
# Swap elements directly, no temp necessary
10+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
11+
swapped = True
12+
# If no two elements were swapped by inner loop, then array is sorted
13+
if not swapped:
14+
break
915
print(f"result: {arr}")
1016
return arr

0 commit comments

Comments
 (0)