-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbitonicSort.py
More file actions
72 lines (55 loc) · 1.53 KB
/
bitonicSort.py
File metadata and controls
72 lines (55 loc) · 1.53 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
import random
import asyncio
from collections import defaultdict
c = defaultdict(lambda: 0)
async def compareInt(a, b):
print(a, '<>', b)
c[a] += 1
c[b] += 1
await asyncio.sleep(2)
if a < b:
return a, b
return b, a
def greatestPowerOfTwoLessThan(n):
assert n > 1
res = 0
next = 1
while next < n:
res = next
next = next*2
return res
async def compare(L, i, j, ascending, comp):
if ascending:
L[i], L[j] = await comp(L[i], L[j])
else:
L[j], L[i] = await comp(L[i], L[j])
async def bitonicSort(L, start, length, ascending, comp):
if length > 1:
m = length//2
await asyncio.gather(
bitonicSort(L, start, m, not ascending, comp),
bitonicSort(L, start+m, length-m, ascending, comp)
)
await bitonicMerge(L, start, length, ascending, comp)
async def bitonicMerge(L, start, length, ascending, comp):
if length > 1:
m = greatestPowerOfTwoLessThan(length)
await asyncio.gather(*[
compare(L, i, i+m, ascending, comp)
for i in range(start, start+length-m)
])
await asyncio.gather(
bitonicMerge(L, start, m, ascending, comp),
bitonicMerge(L, start+m, length-m, ascending, comp)
)
async def sort(L, comp):
await bitonicSort(L, 0, len(L), True, comp)
async def main():
L = list(range(12))
L = L + L
random.shuffle(L)
print(L)
await sort(L, compareInt)
print(L)
asyncio.run(main())
print(c)