From 70812a8cac6165b2ba984ba70c14183328f7a0f6 Mon Sep 17 00:00:00 2001 From: shellhub Date: Thu, 24 Dec 2020 18:41:17 +0800 Subject: [PATCH 1/2] bubble sort recursion --- sorts/bubble_sort_recursion.py | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sorts/bubble_sort_recursion.py diff --git a/sorts/bubble_sort_recursion.py b/sorts/bubble_sort_recursion.py new file mode 100644 index 0000000..f6bbf78 --- /dev/null +++ b/sorts/bubble_sort_recursion.py @@ -0,0 +1,35 @@ +""" +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() From 456b46d9857b078d8856fc7f2c04d8b7075669b2 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 24 Dec 2020 10:43:59 +0000 Subject: [PATCH 2/2] Formatted with psf/black --- sorts/bubble_sort_recursion.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sorts/bubble_sort_recursion.py b/sorts/bubble_sort_recursion.py index f6bbf78..3983fcc 100644 --- a/sorts/bubble_sort_recursion.py +++ b/sorts/bubble_sort_recursion.py @@ -24,7 +24,10 @@ def bubble_sort(array, length: int = 0): swapped = False for i in range(length - 1): if array[i] > array[i + 1]: - array[i], array[i + 1] = array[i + 1], array[i], + array[i], array[i + 1] = ( + array[i + 1], + array[i], + ) swapped = True return array if not swapped else bubble_sort(array, length - 1)