Skip to content

Commit 2b18b06

Browse files
sorts: make recursive bubble sort support comparable items
1 parent be65e47 commit 2b18b06

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

sorts/bubble_sort_recursive.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
1-
def bubble_sort_recursive(arr: list[int]) -> list[int]:
1+
"""
2+
A pure Python implementation of the recursive bubble sort algorithm.
3+
"""
4+
5+
from typing import Protocol
6+
7+
8+
class Comparable(Protocol):
9+
def __lt__(self, other: object, /) -> bool: ...
10+
11+
12+
def bubble_sort_recursive[T: Comparable](arr: list[T]) -> list[T]:
213
"""
3-
Sorts a list of integers using the recursive Bubble Sort algorithm.
14+
Sorts a list of comparable items using the recursive Bubble Sort algorithm.
415
516
>>> bubble_sort_recursive([5, 1, 4, 2, 8])
617
[1, 2, 4, 5, 8]
@@ -12,14 +23,22 @@ def bubble_sort_recursive(arr: list[int]) -> list[int]:
1223
[1, 2, 3, 3]
1324
>>> bubble_sort_recursive([-1, 5, 0, -2])
1425
[-2, -1, 0, 5]
26+
>>> bubble_sort_recursive(["banana", "apple", "cherry"])
27+
['apple', 'banana', 'cherry']
28+
>>> bubble_sort_recursive([3.14, 1.5, 2.7])
29+
[1.5, 2.7, 3.14]
30+
>>> bubble_sort_recursive([1, "two"]) # doctest: +ELLIPSIS
31+
Traceback (most recent call last):
32+
...
33+
TypeError: ...
1534
"""
1635
n = len(arr)
1736
if n <= 1:
1837
return arr
1938

2039
swapped = False
2140
for i in range(n - 1):
22-
if arr[i] > arr[i + 1]:
41+
if arr[i + 1] < arr[i]:
2342
arr[i], arr[i + 1] = arr[i + 1], arr[i]
2443
swapped = True
2544

0 commit comments

Comments
 (0)