Skip to content

Commit 793e33d

Browse files
committed
Add bubble_sort_optimized with early termination
1 parent a051ab5 commit 793e33d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

sorts/bubble_sort_optimized.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""Bubble Sort with early termination optimization."""
2+
3+
4+
def bubble_sort_optimized(arr: list[float]) -> list[float]:
5+
"""
6+
Sort a list using bubble sort with early termination.
7+
8+
Stops early if no swaps occur in a pass (already sorted).
9+
10+
>>> bubble_sort_optimized([64, 34, 25, 12, 22, 11, 90])
11+
[11, 12, 22, 25, 34, 64, 90]
12+
>>> bubble_sort_optimized([1, 2, 3])
13+
[1, 2, 3]
14+
>>> bubble_sort_optimized([])
15+
[]
16+
>>> bubble_sort_optimized([5])
17+
[5]
18+
"""
19+
n = len(arr)
20+
for i in range(n):
21+
swapped = False
22+
for j in range(n - i - 1):
23+
if arr[j] > arr[j + 1]:
24+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
25+
swapped = True
26+
if not swapped:
27+
break
28+
return arr

0 commit comments

Comments
 (0)