forked from souravjain540/Basic-Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Bubble_Sort.py
58 lines (46 loc) · 1.59 KB
/
Bubble_Sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Python Program for implementation of
# Recursive Bubble sort
class bubbleSort:
def __init__(self, array):
self.array = array
self.length = len(array)
def __str__(self):
return " ".join([str(x)
for x in self.array])
def bubbleSortRecursive(self, n=None):
if n is None:
n = self.length
count = 0
# Base case
if n == 1:
return
# One pass of bubble sort. After
# this pass, the largest element
# is moved (or bubbled) to end.
for i in range(n - 1):
if self.array[i] > self.array[i + 1]:
self.array[i], self.array[i +
1] = self.array[i + 1], self.array[i]
count = count + 1
# Check if any recursion happens or not
# If any recursion is not happen then return
if (count==0):
return
# Largest element is fixed,
# recur for remaining array
self.bubbleSortRecursive(n - 1)
# Driver Code
def main():
array = [64, 34, 25, 12, 22, 11, 90]
sort = bubbleSort(array)
sort.bubbleSortRecursive()
print("Sorted array :\n", sort)
# Tests ('pip install pytest'; run with 'pytest Bubble_Sort.py')
def test_result_in_order():
array = [64, 34, 25, 12, 22, 11, 90]
sort = bubbleSort(array)
sort.bubbleSortRecursive()
for i in range(sort.length-1):
assert sort.array[i] < sort.array[i+1]
if __name__ == "__main__":
main()