diff --git a/code_to_optimize/bubble_sort_method.py b/code_to_optimize/bubble_sort_method.py index 962fde339..8feb758f4 100644 --- a/code_to_optimize/bubble_sort_method.py +++ b/code_to_optimize/bubble_sort_method.py @@ -7,11 +7,14 @@ def __init__(self, x=0): def sorter(self, arr): print("codeflash stdout : BubbleSorter.sorter() called") - for i in range(len(arr)): - for j in range(len(arr) - 1): + n = len(arr) + for i in range(n): + swapped = False # Early exit if no elements were swapped + for j in range(n - 1 - i): # Skip the last i elements (already sorted) if arr[j] > arr[j + 1]: - temp = arr[j] - arr[j] = arr[j + 1] - arr[j + 1] = temp + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + if not swapped: + break print("stderr test", file=sys.stderr) return arr