Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions code_to_optimize/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
def sorter(arr):
print("codeflash stdout: Sorting list")
for i in range(len(arr)):
for j in range(len(arr) - 1):
n = len(arr)
# Optimized bubble sort: on each pass, the largest elements settle at the end.
for i in range(n):
swapped = False
# Reduce inner loop range for already-sorted tail
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
# Swap elements directly (no temp variable needed)
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# Early exit if no swaps, array is already sorted
if not swapped:
break
print(f"result: {arr}")
return arr
Loading