Explanation:
Here, we created five functions Exchange(), compare(), bitonicmerge(), recbitonic(), and main().The Exchange() function is used to swap values of two variable. The compare() function is used to compare array element and perform swapping. The bitonicmerge(), recbitonic() functions are used to sort bitonic sequence in ascending order.
In the main() function, we read array elements from the user. Then we sorted the elements of the array using the recbitonic() function and printed the sorted array on the console screen.
// C program to implement Bitonic sort algorithm
#include <stdio.h>
#define MAX 8
int arr[MAX];
int up = 1;
int down = 0;
void Exchange(int* num1, int* num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
void compare(int i, int j, int dir)
{
int t;
if (dir == (arr[i] > arr[j])) {
Exchange(&arr[i], &arr[j]);
}
}
void bitonicmerge(int low, int c, int dir)
{
int k = 0;
int i = 0;
if (c > 1) {
k = c / 2;
i = low;
while (i < low + k) {
compare(i, i + k, dir);
i++;
}
bitonicmerge(low, k, dir);
bitonicmerge(low + k, k, dir);
}
}
void recbitonic(int low, int v, int dir)
{
int k = 0;
if (v > 1) {
k = v / 2;
recbitonic(low, k, up);
recbitonic(low + k, k, down);
bitonicmerge(low, v, dir);
}
}
int main()
{
int i = 0;
printf("Enter array elements:\n");
while (i < MAX) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}
recbitonic(0, MAX, up);
printf("Sorted Array: \n");
i = 0;
while (i < MAX) {
printf("%d ", arr[i]);
i++;
}
printf("\n");
return 0;
}
Output:
RUN 1:
Enter array elements:
Element[0]: 23
Element[1]: 45
Element[2]: 65
Element[3]: 23
Element[4]: 87
Element[5]: 56
Element[6]: 98
Element[7]: 34
Sorted Array:
23 23 34 45 56 65 87 98
RUN 2:
Enter array elements:
Element[0]: 10
Element[1]: 12
Element[2]: 34
Element[3]: 5
Element[4]: 15
Element[5]: 10
Element[6]: 25
Element[7]: 67
Sorted Array:
5 10 10 12 15 25 34 67