Skip to content

Commit eec116a

Browse files
committed
sorts: make bubble_sort_recursive accept any Comparable items
1 parent a4c1df1 commit eec116a

1 file changed

Lines changed: 17 additions & 2 deletions

File tree

‎sorts/bubble_sort_recursive.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
1-
def bubble_sort_recursive(arr: list[int]) -> list[int]:
1+
from typing import Any, Protocol
2+
3+
4+
class Comparable(Protocol):
5+
def __lt__(self, other: Any, /) -> bool: ...
6+
7+
8+
def bubble_sort_recursive[T: Comparable](arr: list[T]) -> list[T]:
29
"""
3-
Sorts a list of integers using the recursive Bubble Sort algorithm.
10+
Sorts a collection of comparable items using the recursive Bubble Sort algorithm.
411

512
>>> bubble_sort_recursive([5, 1, 4, 2, 8])
613
[1, 2, 4, 5, 8]
@@ -12,6 +19,14 @@ def bubble_sort_recursive(arr: list[int]) -> list[int]:
1219
[1, 2, 3, 3]
1320
>>> bubble_sort_recursive([-1, 5, 0, -2])
1421
[-2, -1, 0, 5]
22+
>>> bubble_sort_recursive(["c", "a", "b"])
23+
['a', 'b', 'c']
24+
>>> bubble_sort_recursive([2.5, -1, 0.0])
25+
[-1, 0.0, 2.5]
26+
>>> bubble_sort_recursive([1, "a"])
27+
Traceback (most recent call last):
28+
...
29+
TypeError: '>' not supported between instances of 'int' and 'str'
1530
"""
1631
n = len(arr)
1732
if n <= 1:

0 commit comments

Comments
 (0)