-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path106-bitonic_sort.c
executable file
·77 lines (72 loc) · 1.59 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
#include "sort.h"
/**
* bitonic_compare - sort bitonic algorithm
* @up: direction of sorting
* @array: sub-array to sort
* @size: size of the sub-array
*/
void bitonic_compare(char up, int *array, size_t size)
{
size_t i, eva;
int swap;
eva = size / 2;
for (i = 0; i < eva; i++)
{
if ((array[i] > array[i + eva]) == up)
{
swap = array[i];
array[i] = array[i + eva];
array[i + eva] = swap;
}
}
}
/**
* bitonic_merge - recursion to mergess ub-arrays
* @up: direction of sorting
* @array: sub-array to sort
* @size: size of the sub-array
*
* Return: void
*/
void bitonic_merge(char up, int *array, size_t size)
{
if (size < 2)
return;
bitonic_compare(up, array, size);
bitonic_merge(up, array, size / 2);
bitonic_merge(up, array + (size / 2), size / 2);
}
/**
* bit_sort - recursive bitonic sort algorithm
* @up: direction of sorting
* @array: sub-array to sort
* @size: size of the sub-array
* @t: total size of the original array
*
* Return: void
*/
void bit_sort(char up, int *array, size_t size, size_t t)
{
if (size < 2)
return;
printf("Merging [%lu/%lu] (%s):\n", size, t, (up == 1) ? "UP" : "DOWN");
print_array(array, size);
bit_sort(1, array, size / 2, t);
bit_sort(0, array + (size / 2), size / 2, t);
bitonic_merge(up, array, size);
printf("Result [%lu/%lu] (%s):\n", size, t, (up == 1) ? "UP" : "DOWN");
print_array(array, size);
}
/**
* bitonic_sort - sorts an array in ascending order
* @array: array to sort
* @size: size of the array
*
* Return: void
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
bit_sort(1, array, size, size);
}