forked from Obelem/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path106-bitonic_sort.c
83 lines (77 loc) · 1.79 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
#include "sort.h"
#include <stdio.h>
/**
* bitonic_compare - sort the values in a sub-array with respect to
* the Bitonic sort algorithm
* @up: direction of sorting
* @array: sub-array to sort
* @size: size of the sub-array
*
* Return: void
*/
void bitonic_compare(char up, int *array, size_t size)
{
size_t i, dist;
int swap;
dist = size / 2;
for (i = 0; i < dist; i++)
{
if ((array[i] > array[i + dist]) == up)
{
swap = array[i];
array[i] = array[i + dist];
array[i + dist] = swap;
}
}
}
/**
* bitonic_merge - recursive function that merges two sub-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 function using the 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 of integers in ascending order using
* the Bitonic sort algorithm
* @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);
}