Skip to content

Commit d4b4b7b

Browse files
authored
Merge pull request TheAlgorithms#321 from aldokkani/master
Break if the collection is sorted
2 parents cb6c82c + 9489e85 commit d4b4b7b

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

sorts/bubble_sort.py

Lines changed: 3 additions & 1 deletion
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)