forked from hansrajdas/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble_sort.py
40 lines (32 loc) · 820 Bytes
/
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
#!/usr/bin/python
# Date: 2018-09-08
#
# Description:
# Implement bubble sort.
#
# Approach:
# Compares adjacent elements and pushes to it's required extreme. Here while
# sorting in ascending order largest element reaches at last place after first
# iteration of outer loop.
#
# Complexity:
# O(n^2)
def main():
a = []
n = input ("Enter number of elements: ")
for i in range (n):
x = input ("Enter value of a[%d]: " % i)
a.append(x)
for i in range(n):
swap_flag = False;
for j in range(0, n - 1 - i, 1):
if (a[j] > a[j + 1]):
a[j], a[j+1] = a[j+1], a[j]
swap_flag = True;
if not swap_flag:
break
# Print sorted array
for i in range(n):
print a[i]
if __name__ == '__main__':
main()