Skip to content

Commit 5814fbb

Browse files
⚡️ Speed up method BubbleSorter.sorter by 144%
Here's an optimized version of your program. Improvements. - Reduce repeated computation of `len(arr)` in loops. - Make the bubble sort algorithm more efficient by stopping when no swaps occur (early exit). - Remove unnecessary variable assignments (`temp`). This is still bubble sort (for correctness), but with early-termination and less memory/operations. The function signatures, return values, and comments are preserved as requested.
1 parent 1fb06ec commit 5814fbb

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

code_to_optimize/bubble_sort_method.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ def __init__(self, x=0):
77

88
def sorter(self, arr):
99
print("codeflash stdout : BubbleSorter.sorter() called")
10-
for i in range(len(arr)):
11-
for j in range(len(arr) - 1):
10+
n = len(arr)
11+
for i in range(n):
12+
swapped = False # Early exit if no elements were swapped
13+
for j in range(n - 1 - i): # Skip the last i elements (already sorted)
1214
if arr[j] > arr[j + 1]:
13-
temp = arr[j]
14-
arr[j] = arr[j + 1]
15-
arr[j + 1] = temp
15+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
16+
swapped = True
17+
if not swapped:
18+
break
1619
print("stderr test", file=sys.stderr)
1720
return arr

0 commit comments

Comments
 (0)