-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path106-bitonic_sort.c
89 lines (82 loc) · 1.91 KB
/
106-bitonic_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "sort.h"
/**
* swap - swap two elements of the array
* @array: array to swap its elements
* @x: first element
* @y: second element
* Return: Nothing
*/
void swap(int *array, int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
/**
* bitonic_merge - merge two sub arrays after sorting
* @array: array to be sorted
* @low_idx: first index of array/sub array
* @count: number of elements to be checked in base case
* @dir: direction of sorting
* @size: size of array
* Return: Nothing
*/
void bitonic_merge(int *array, int low_idx, int count, int dir, size_t size)
{
int k, i;
if (count > 1)
{
k = count / 2;
for (i = low_idx; i < low_idx + k; i++)
{
if (dir == (array[i] > array[i + k]))
{
swap(array, i, i + k);
}
}
bitonic_merge(array, low_idx, k, dir, size);
bitonic_merge(array, low_idx + k, k, dir, size);
}
}
/**
* sort - divide the array into two sub arrays
* @array: array to be sorted
* @low_idx: first index of array/sub array
* @count: number of elements to be checked in base case
* @dir: direction of sorting
* @size: size of array
* Return: Nothing
*/
void sort(int *array, int low_idx, int count, int dir, size_t size)
{
int k;
char *str;
if (count > 1)
{
if (dir == 1)
str = "UP";
else
str = "DOWN";
k = count / 2;
printf("Merging [%d/%ld] (%s):\n", count, size, str);
print_array(array + low_idx, count);
sort(array, low_idx, k, 1, size);
sort(array, low_idx + k, k, 0, size);
bitonic_merge(array, low_idx, count, dir, size);
printf("Result [%d/%ld] (%s):\n", count, size, str);
print_array(array + low_idx, count);
}
}
/**
* bitonic_sort - sorts an array of integers using the Bitonic sort algorithm
* @array: array to be sorted
* @size: size of the array
* Return: Nothing
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
sort(array, 0, size, 1, size);
}