Skip to content

Commit 12c8bf3

Browse files
committed
Added: Optimized bubble sort when array is already sorted
1 parent 33a0a07 commit 12c8bf3

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Algorithm/Sorting/bubble_sort.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"""
1818

1919

20-
arr = [1, 2, 9, 6, 4, 3, 5, 8, 7, 10]
20+
arr = list(map(int, input().split()))
2121

2222
for i in range(len(arr)):
2323
# Last ith elements are already sorted
@@ -26,4 +26,28 @@
2626
if arr[j] > arr[j+1]:
2727
arr[j], arr[j+1] = arr[j+1], arr[j]
2828

29+
print(*arr)
30+
31+
# Bubble Sort Algorithm in O(n) time complexity when array is already sorted
32+
33+
"""
34+
In bubble sort we swap elements only when current element is
35+
greater than next element. Keeping this in mind in an iteration,
36+
if no swap is performed means that all the next elements are in
37+
ascending order so we don't need to perform swaps for those elements.
38+
And we can stop sorting.
39+
"""
40+
41+
for i in range(len(arr)):
42+
# Last ith elements are already sorted
43+
# so exclude them for comparison in current iteration
44+
swap = False
45+
for j in range(len(arr)-i-1):
46+
if arr[j] > arr[j+1]:
47+
arr[j], arr[j+1] = arr[j+1], arr[j]
48+
swap = True
49+
50+
if swap == False:
51+
break
52+
2953
print(*arr)

0 commit comments

Comments
 (0)