-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathbubble_sort_optimized.py
More file actions
28 lines (24 loc) · 766 Bytes
/
bubble_sort_optimized.py
File metadata and controls
28 lines (24 loc) · 766 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""Bubble Sort with early termination optimization."""
def bubble_sort_optimized(arr: list[float]) -> list[float]:
"""
Sort a list using bubble sort with early termination.
Stops early if no swaps occur in a pass (already sorted).
>>> bubble_sort_optimized([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]
>>> bubble_sort_optimized([1, 2, 3])
[1, 2, 3]
>>> bubble_sort_optimized([])
[]
>>> bubble_sort_optimized([5])
[5]
"""
n = len(arr)
for i in range(n):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr