Skip to content

Commit 42ae7a6

Browse files
feat: add recursive bubble sort algorithm with doctests and type hints (#13424)
* feat: add recursive bubble sort algorithm with doctests and type hints Implement recursive Bubble Sort algorithm with doctests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Refactor bubble_sort_recursive function Refactor bubble_sort_recursive to use built-in list type and improve return statement. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent b890306 commit 42ae7a6

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

sorts/bubble_sort_recursive.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def bubble_sort_recursive(arr: list[int]) -> list[int]:
2+
"""
3+
Sorts a list of integers using the recursive Bubble Sort algorithm.
4+
5+
>>> bubble_sort_recursive([5, 1, 4, 2, 8])
6+
[1, 2, 4, 5, 8]
7+
>>> bubble_sort_recursive([])
8+
[]
9+
>>> bubble_sort_recursive([1])
10+
[1]
11+
>>> bubble_sort_recursive([3, 3, 2, 1])
12+
[1, 2, 3, 3]
13+
>>> bubble_sort_recursive([-1, 5, 0, -2])
14+
[-2, -1, 0, 5]
15+
"""
16+
n = len(arr)
17+
if n <= 1:
18+
return arr
19+
20+
swapped = False
21+
for i in range(n - 1):
22+
if arr[i] > arr[i + 1]:
23+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
24+
swapped = True
25+
26+
if not swapped:
27+
return arr
28+
29+
return [*bubble_sort_recursive(arr[:-1]), arr[-1]]
30+
31+
32+
if __name__ == "__main__":
33+
import doctest
34+
35+
doctest.testmod()

0 commit comments

Comments
 (0)