-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.py
More file actions
82 lines (68 loc) · 1.99 KB
/
bubble_sort.py
File metadata and controls
82 lines (68 loc) · 1.99 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#import timeit
def bubble(l):
N = len(l)
for j in range(1, N + 1):
swaps = False
for i in range(N - j):
k = i + 1
if l[i] > l[k]:
l[i], l[k] = l[k], l[i]
swaps = True
if not swaps:
break
return l
def insertion(l):
for i in range(1, len(l)):
k, j = l[i], i - 1
while j >= 0 and k < l[j]:
l[j + 1] = l[j]
j -= 1
l[j + 1] = k
return l
def merge(l):
if len(l) > 1:
mid = len(l) // 2
left, right, i, j, k = l[:mid], l[mid:], 0, 0, 0
merge(left)
merge(right)
while i < len(left) and j < len(right):
if left[i] < right[j]:
l[k] = left[i]
i += 1
else:
l[k] = right[j]
j += 1
k += 1
while i < len(left):
l[k] = left[i]
i += 1
k += 1
while j < len(right):
l[k] = right[j]
j += 1
k += 1
return l
def quicksort(l):
if len(l) < 2: return l
pivot = l[0]
less, greater = [i for i in l[1:] if i <= pivot], [i for i in l[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
"""
n = [5, 9, 4, 2, 11, 15, 23, 31, 1, 6]
def run_bubble(): return bubble(n.copy())
def run_insertion(): return insertion(n.copy())
def run_merge(): return merge(n.copy())
def run_quicksort(): return quicksort(n.copy())
b_result = run_bubble()
b_time = timeit.timeit(run_bubble, number=1) * 1000
i_result = run_insertion()
i_time = timeit.timeit(run_insertion, number=1) * 1000
m_result = run_merge()
m_time = timeit.timeit(run_merge, number=1) * 1000
q_result = run_quicksort()
q_time = timeit.timeit(run_quicksort, number=1) * 1000
print(f" Bubble: {b_result} ({b_time:.3f} ms)")
print(f"Insertion: {i_result} ({i_time:.3f} ms)")
print(f" Merge: {m_result} ({m_time:.3f} ms)")
print(f"QuickSort: {q_result} ({q_time:.3f} ms)")
"""