diff --git a/code_to_optimize/bubble_sort.py b/code_to_optimize/bubble_sort.py index 9e97f63a0..45e2b15a2 100644 --- a/code_to_optimize/bubble_sort.py +++ b/code_to_optimize/bubble_sort.py @@ -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) + for i in range(n): + swapped = False + for j in range(n - 1 - i): 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 + # Handle cases where swap detection gives only minor speedup + # Continue full loop if list is small or nearly sorted, do not break early + # (i.e., ignore the swapped/break optimization for insignificant gains) + # Commenting out the early break + # if not swapped: + # break print(f"result: {arr}") return arr