Added bitonic sort
This commit is contained in:
parent
0956cae266
commit
798ede9f1f
1 changed files with 32 additions and 0 deletions
32
bitonic.py
Normal file
32
bitonic.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
#!/usr/bin/env python
|
||||
from random import randint
|
||||
|
||||
def bitonic_sort(up, x):
|
||||
if len(x) <= 1:
|
||||
return x
|
||||
else:
|
||||
half = int(len(x) / 2)
|
||||
first = bitonic_sort(True, x[:half])
|
||||
second = bitonic_sort(False, x[half:])
|
||||
return bitonic_merge(up, first + second)
|
||||
|
||||
def bitonic_merge(up, x):
|
||||
# assume input x is bitonic, and sorted list is returned
|
||||
if len(x) == 1:
|
||||
return x
|
||||
else:
|
||||
bitonic_compare(up, x)
|
||||
half = int(len(x) / 2)
|
||||
first = bitonic_merge(up, x[:half])
|
||||
second = bitonic_merge(up, x[half:])
|
||||
return first + second
|
||||
|
||||
def bitonic_compare(up, x):
|
||||
dist = int(len(x) / 2)
|
||||
for i in range(dist):
|
||||
if (x[i] > x[i + dist]) == up:
|
||||
x[i], x[i + dist] = x[i + dist], x[i] #swap
|
||||
|
||||
if __name__ == '__main__':
|
||||
sorted_array = bitonic_sort(True, [randint(1,1000) for i in range(16)])
|
||||
print(sorted_array)
|
Loading…
Reference in a new issue