-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.py
More file actions
31 lines (27 loc) · 771 Bytes
/
bubble_sort.py
File metadata and controls
31 lines (27 loc) · 771 Bytes
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
import numpy as np
def bubbleSort(num):
"""
Bubble sort algorithm.
Input: number sequence
Output: number sequence (ascending order)
Complexity: Worst-case O(n^2), Best-case O(n)
"""
size = len(num)
swapped = True
for i in range(size):
if swapped is not True:
return num
swapped = False
for j in range(size - i - 1):
if num[j] > num[j + 1]:
swapped = True
num[j], num[j + 1] = num[j + 1], num[j]
return num
if __name__ == '__main__':
low, high, size = 0, 100, 20
num = np.random.randint(low, high, size)
print('----before sort----')
print(num)
sorted_num = bubbleSort(num)
print('----after sort----')
print(sorted_num)