diff --git a/code_to_optimize/bubble_sort.py b/code_to_optimize/bubble_sort.py index 9e97f63a0..76699867a 100644 --- a/code_to_optimize/bubble_sort.py +++ b/code_to_optimize/bubble_sort.py @@ -1,10 +1,16 @@ def sorter(arr): print("codeflash stdout: Sorting list") - for i in range(len(arr)): - for j in range(len(arr) - 1): + n = len(arr) + for i in range(n): + swapped = False + # After each i, the last i elements are in place + 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 necessary + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + # If no two elements were swapped by inner loop, then array is sorted + if not swapped: + break print(f"result: {arr}") return arr