2020-09-10 08:31:26 +00:00
|
|
|
def bubble_sort(list_data: list, length: int = 0) -> list:
|
2020-01-04 15:03:55 +00:00
|
|
|
"""
|
|
|
|
It is similar is bubble sort but recursive.
|
2020-09-10 08:31:26 +00:00
|
|
|
:param list_data: mutable ordered sequence of elements
|
|
|
|
:param length: length of list data
|
2020-01-04 15:03:55 +00:00
|
|
|
:return: the same list in ascending order
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([0, 5, 2, 3, 2], 5)
|
2020-01-04 15:03:55 +00:00
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([], 0)
|
2020-01-04 15:03:55 +00:00
|
|
|
[]
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([-2, -45, -5], 3)
|
2020-01-04 15:03:55 +00:00
|
|
|
[-45, -5, -2]
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([-23, 0, 6, -4, 34], 5)
|
2020-01-04 15:03:55 +00:00
|
|
|
[-23, -4, 0, 6, 34]
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([-23, 0, 6, -4, 34], 5) == sorted([-23, 0, 6, -4, 34])
|
2020-01-04 15:03:55 +00:00
|
|
|
True
|
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort(['z','a','y','b','x','c'], 6)
|
2020-01-04 15:03:55 +00:00
|
|
|
['a', 'b', 'c', 'x', 'y', 'z']
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
>>> bubble_sort([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
|
|
|
|
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
|
2020-01-04 15:03:55 +00:00
|
|
|
"""
|
2020-09-10 08:31:26 +00:00
|
|
|
length = length or len(list_data)
|
|
|
|
swapped = False
|
|
|
|
for i in range(length - 1):
|
|
|
|
if list_data[i] > list_data[i + 1]:
|
|
|
|
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
|
|
|
|
swapped = True
|
2020-01-04 15:03:55 +00:00
|
|
|
|
2020-09-10 08:31:26 +00:00
|
|
|
return list_data if not swapped else bubble_sort(list_data, length - 1)
|
2020-01-04 15:03:55 +00:00
|
|
|
|
2020-01-08 13:06:53 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-09-10 08:31:26 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|