-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path106-bitonic_sort.c
89 lines (78 loc) · 2.01 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 - swaps two ints.
* @a: the first int.
* @b: the second.
* Return: Nothing (void).
*/
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/**
* bitonic_merge - Sorts a bitonic sequence inside an array.
* @array: array of ints.
* @size: the size of the array.
* @start: the starting index.
* @sq: the size of the sequence.
* @direction: 'U' for UP and 'D' for DOWN
* Return: nothing (void).
*/
void bitonic_merge(int *array, size_t size, size_t start,
size_t sq, char direction)
{
size_t i, jump = sq / 2;
if (sq > 1)
{
for (i = start; i < start + jump; i++)
{
if ((direction == 'U' && array[i] > array[i + jump]) ||
(direction == 'D' && array[i] < array[i + jump]))
swap(array + i, array + i + jump);
}
bitonic_merge(array, size, start, jump, direction);
bitonic_merge(array, size, start + jump, jump, direction);
}
}
/**
* bitonic_sequence - converts an array into bitonic sequence.
* @array: array of int.
* @size: size of the array.
* @start: the starting index.
* @sq: the size of a block of the building.
* @direction: the direction to sort.
* Return: Nothing (void).
*/
void bitonic_sequence(int *array, size_t size,
size_t start, size_t sq, char direction)
{
size_t c = sq / 2;
if (sq > 1)
{
printf("Merging [%lu/%lu] (%s):\n",
sq, size, (direction == 'U') ? "UP" : "DOWN");
print_array(array + start, sq);
bitonic_sequence(array, size, start, c, 'U');
bitonic_sequence(array, size, start + c, c, 'D');
bitonic_merge(array, size, start, sq, direction);
printf("Result [%lu/%lu] (%s):\n",
sq, size, (direction == 'U') ? "UP" : "DOWN");
print_array(array + start, sq);
}
}
/**
* bitonic_sort - sorts an array of integers in ascending order using the
* Bitonic sort algorithm.
* @array: array of int.
* @size: size of the array.
* Return: Nothing (void).
*
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
bitonic_sequence(array, size, 0, size, 'U');
}