File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments