From 9489e8512df9e073ac019c75f827c03fe64242dd Mon Sep 17 00:00:00 2001 From: Hossam Al-Dokkani Date: Sat, 23 Jun 2018 17:01:06 +0200 Subject: [PATCH] Break if the collection is sorted --- sorts/bubble_sort.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index e1bdf3189..e28e7aa4f 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -32,10 +32,12 @@ def bubble_sort(collection): """ length = len(collection) for i in range(length): + swapped = False for j in range(length-1): if collection[j] > collection[j+1]: + swapped = True collection[j], collection[j+1] = collection[j+1], collection[j] - + if not swapped: break # Stop iteration if the collection is sorted. return collection