From 4449c775e7dec97f69c5d45ee7f4553ccc32e825 Mon Sep 17 00:00:00 2001 From: RevathiKillampalli Date: Sat, 26 Oct 2024 20:54:47 +0530 Subject: [PATCH] Update bubbleSort.py this may reduce number of iterations --- bubbleSort.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bubbleSort.py b/bubbleSort.py index f421d0c..55f7728 100644 --- a/bubbleSort.py +++ b/bubbleSort.py @@ -1,9 +1,13 @@ def bubble_sort(arr): n = len(arr) for i in range(n): + swapped=False for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped=True + if not swapped: + break return arr print(bubble_sort([64, 34, 25, 12, 22, 11, 90])) # Expected: [11, 12, 22, 25, 34, 64, 90]