Skip to content

Commit 57123df

Browse files
⚡️ Speed up function sorter by 74%
Here is an optimized version. Your original code is an unoptimized bubble sort with unnecessary repeated traversals. We can improve it by. - Avoiding repeated calls to `len(arr)` in the loop - Stopping early if no swaps occur in a pass - Using tuple unpacking for swapping, which is faster in Python - Reducing the inner loop traversal on each pass (classic bubble sort optimization) The fastest general-purpose list sort in Python is the built-in `list.sort()`, but since function signatures and return values must remain identical, and the question is about code speed-up, here is an improved bubble sort still with explanatory prints. This is the fastest possible bubble sort using your structure and prints, with minimal memory usage. If pure speed is needed (and in production, if prints are not strictly required), simply using `arr.sort()` is vastly faster, but the loop-based sorting is preserved as requested.
1 parent 0d566bf commit 57123df

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
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+
for j in range(n - 1 - i):
57
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
8+
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Faster tuple unpacking
9+
swapped = True
10+
if not swapped:
11+
break # Stop if the list is already sorted
912
print(f"result: {arr}")
1013
return arr

0 commit comments

Comments
 (0)