Skip to content

bubble sort recursion #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 24, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions sorts/bubble_sort_recursion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
https://en.wikipedia.org/wiki/Bubble_sort
"""


def bubble_sort(array, length: int = 0):
"""
:param array: the array to be sorted.
:param length: the length of array.
:return: sorted array.
>>> import random
>>> array = random.sample(range(-50, 50), 100)
>>> bubble_sort(array) == sorted(array)
True
>>> import string
>>> array = random.choices(string.ascii_letters + string.digits, k = 100)
>>> bubble_sort(array) == sorted(array)
True
>>> array = [random.uniform(-50.0, 50.0) for i in range(100)]
>>> bubble_sort(array) == sorted(array)
True
"""
length = length or len(array)
swapped = False
for i in range(length - 1):
if array[i] > array[i + 1]:
array[i], array[i + 1] = (
array[i + 1],
array[i],
)
swapped = True
return array if not swapped else bubble_sort(array, length - 1)


if __name__ == "__main__":
from doctest import testmod

testmod()