# Bitonic Sort

Bitonic sort is a parallel sorting algorithm which performs O(n2 log n) comparisons. Although, the number of comparisons are more than that in any other popular sorting algorithm, It performs better for the parallel implementation because elements are compared in predefined sequence which must not be depended upon the data being sorted. The predefined sequence is called Bitonic sequence.

### What is Bitonic Sequence ?

In order to understand Bitonic sort, we must understand Bitonic sequence. Bitonic sequence is the one in which, the elements first comes in increasing order then start decreasing after some particular index. An array A[0... i ... n-1] is called Bitonic if there exist an index i such that,

where, 0 <= i <= n-1. A rotation of Bitonic sort is also Bitonic.

### How to convert Random sequence to Bitonic sequence ?

Consider a sequence A[ 0 ... n-1] of n elements. First start constructing Bitonic sequence by using 4 elements of the sequence. Sort the first 2 elements in ascending order and the last 2 elements in descending order, concatenate this pair to form a Bitonic sequence of 4 elements. Repeat this process for the remaining pairs of element until we find a Bitonic sequence. After this step, we get the Bitonic sequence for the given sequence as 2, 10, 20, 30, 5, 5, 4, 3.

## Bitonic Sorting :

Bitonic sorting mainly involves the following basic steps.

1. Form a Bitonic sequence from the given random sequence which we have formed in the above step. We can consider it as the first step in our procedure. After this step, we get a sequence whose first half is sorted in ascending order while second step is sorted in descending order.
2. Compare first element of first half with the first element of the second half, then second element of the first half with the second element of the second half and so on. Swap the elements if any element in the second half is found to be smaller.
3. After the above step, we got all the elements in the first half smaller than all the elements in the second half. The compare and swap results into the two sequences of n/2 length each. Repeat the process performed in the second step recursively onto every sequence until we get single sorted sequence of length n.

The whole procedure involved in Bitonic sort is described in the following image. ## Complexity

Complexity Best Case Average Case Worst Case
Time Complexity O(log 2 n) O(log 2 n) O(log 2 n)
Space Complexity O(n log 2 n)

### C Program

Output:

```Sorted array:
1 1 2 3 10 21 23 45
```

### Java

Output:

```Sorted array:

1	1	2	3	10	21	23	45
```

C#

Next TopicCocktail Sort    