🌐 AI搜索 & 代理 主页
Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add bubble_sort_optimized with early termination
  • Loading branch information
tushi145 committed Nov 29, 2025
commit 793e33d0745810cfa635fe20f6fbb96f165b39a2
28 changes: 28 additions & 0 deletions sorts/bubble_sort_optimized.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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