Skip to content

Commit 428aeb8

Browse files
authored
feat: add recursive bubble sort algorithm with doctests and type hints
Implement recursive Bubble Sort algorithm with doctests.
1 parent 788d95b commit 428aeb8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

sorts/bubble_sort_recursive.py

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

0 commit comments

Comments
 (0)