From 798ede9f1f3084d4e4559e07031ced1547ebed73 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Wed, 10 Feb 2016 11:22:39 +0100 Subject: [PATCH] Added bitonic sort --- bitonic.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 bitonic.py diff --git a/bitonic.py b/bitonic.py new file mode 100644 index 0000000..3dcbf79 --- /dev/null +++ b/bitonic.py @@ -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)