one-file-projects/bitonic.py

33 lines
913 B
Python

#!/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)