Skip to content

Commit 07a483d

Browse files
realDuYuanChaogithub-actions
and
github-actions
authored
bubble sort recursion (#30)
* bubble sort recursion * Formatted with psf/black Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent c28a1b4 commit 07a483d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

sorts/bubble_sort_recursion.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Bubble_sort
3+
"""
4+
5+
6+
def bubble_sort(array, length: int = 0):
7+
"""
8+
:param array: the array to be sorted.
9+
:param length: the length of array.
10+
:return: sorted array.
11+
>>> import random
12+
>>> array = random.sample(range(-50, 50), 100)
13+
>>> bubble_sort(array) == sorted(array)
14+
True
15+
>>> import string
16+
>>> array = random.choices(string.ascii_letters + string.digits, k = 100)
17+
>>> bubble_sort(array) == sorted(array)
18+
True
19+
>>> array = [random.uniform(-50.0, 50.0) for i in range(100)]
20+
>>> bubble_sort(array) == sorted(array)
21+
True
22+
"""
23+
length = length or len(array)
24+
swapped = False
25+
for i in range(length - 1):
26+
if array[i] > array[i + 1]:
27+
array[i], array[i + 1] = (
28+
array[i + 1],
29+
array[i],
30+
)
31+
swapped = True
32+
return array if not swapped else bubble_sort(array, length - 1)
33+
34+
35+
if __name__ == "__main__":
36+
from doctest import testmod
37+
38+
testmod()

0 commit comments

Comments
 (0)