# Python Example – Write a Python code to create a program for Bitonic Sort # (Python Example for Citizen Data Scientist & Business Analyst)

Write a Python code to create a program for Bitonic Sort.

Bitonic Sort: According to rutgers.edu – Bitonic sort is a comparison-based sorting algorithm that can be run in parallel. It focuses on converting a random sequence of numbers into a bitonic sequence, one that monotonically increases, then decreases. Rotations of a bitonic sequence are also bitonic.
More specifically, bitonic sort can be modelled as a type of sorting network. The initial unsorted sequence enters through input pipes, where a series of comparators switch two entries to be in either increasing or decreasing order.

The algorithm, created by Ken Batcher in 1968, consists of two parts. First, the unsorted sequence is built into a bitonic sequence; then, the series is split multiple times into smaller sequences until the input is in sorted order.

Sample Solution:

Python Code:

``````
def compAndSwap(a, i, j, dire):
if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]):
a[i], a[j] = a[j], a[i]

def bitonicMerge(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
for i in range(low, low + k):
compAndSwap(a, i, i + k, dire)
bitonicMerge(a, low, k, dire)
bitonicMerge(a, low + k, k, dire)

def bitonicSort(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
bitonicSort(a, low, k, 1)
bitonicSort(a, low + k, k, 0)
bitonicMerge(a, low, cnt, dire)

def sort(a, N, up):
bitonicSort(a, 0, N, up)

a = []
print("How many numbers u want to enter?");
n = int(input())
print("Input the numbers:");
for i in range(n):
a.append(int(input()))
up = 1

sort(a, n, up)
print("nnSorted array is:")
for i in range(n):
print("%d" % a[i])
``````

Sample Output:

```How many numbers u want to enter?
5
Input the numbers:
25
13
76
59
37

Sorted array is:
13
25
59
76
37```

## Write a Python code to create a program for Bitonic Sort

#### Free Machine Learning & Data Science Coding Tutorials in Python & R for Beginners. Subscribe @ Western Australian Center for Applied Machine Learning & Data Science. ```