Skip to content

Commit 9489e85

Browse files
author
Hossam Al-Dokkani
committed
Break if the collection is sorted
1 parent cb6c82c commit 9489e85

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

sorts/bubble_sort.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,12 @@ def bubble_sort(collection):
3232
"""
3333
length = len(collection)
3434
for i in range(length):
35+
swapped = False
3536
for j in range(length-1):
3637
if collection[j] > collection[j+1]:
38+
swapped = True
3739
collection[j], collection[j+1] = collection[j+1], collection[j]
38-
40+
if not swapped: break # Stop iteration if the collection is sorted.
3941
return collection
4042

4143

0 commit comments

Comments
 (0)