Added bitonic sort

This commit is contained in:
madmaurice 2016-02-10 11:22:39 +01:00
parent 0956cae266
commit 798ede9f1f

32
bitonic.py Normal file
View 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)