-
Notifications
You must be signed in to change notification settings - Fork 0
/
106-bitonic_sort.c
executable file
·82 lines (73 loc) · 2.15 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
#include "sort.h"
void bitonic_sort(int *array, size_t size);
void bitonic_seq(int *array, size_t size, size_t start, size_t seq, char flow);
void bitonic_merge(int *array, size_t size, size_t start, size_t seq,
char flow);
/**
* bitonic_sort - Sorts an array of integers in ascending order.
*
* @array: The array to be sorted.
* @size: The size of array.
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
bitonic_seq(array, size, 0, size, UP);
}
/**
* bitonic_seq - Convert an array of integers into bitonic seq.
*
* @array: An array of integers.
* @size: The size of the array.
* @start: The starting index of a block of the building bitonic sequence.
* @seq: The size of a block of the building bitonic sequence.
* @flow: The direction to sort the bitonic sequence block in.
*/
void bitonic_seq(int *array, size_t size, size_t start, size_t seq, char flow)
{
size_t cut = seq / 2;
char *str = (flow == UP) ? "UP" : "DOWN";
if (seq > 1)
{
printf("Merging [%lu/%lu] (%s):\n", seq, size, str);
print_array(array + start, seq);
bitonic_seq(array, size, start, cut, UP);
bitonic_seq(array, size, start + cut, cut, DOWN);
bitonic_merge(array, size, start, seq, flow);
printf("Result [%lu/%lu] (%s):\n", seq, size, str);
print_array(array + start, seq);
}
}
/**
* bitonic_merge - Sort a bitonic sequence inside an array of integers.
*
* @array: An array of integers.
* @size: The size of the array.
* @start: The starting index of the sequence in array to sort.
* @seq: The size of the sequence to sort.
* @flow: The direction to sort in.
*/
void bitonic_merge(int *array, size_t size, size_t start, size_t seq,
char flow)
{
size_t index, jump = seq / 2;
int tmp, *arr1, *arr2;
if (seq > 1)
{
for (index = start; index < start + jump; index++)
{
arr1 = array + index;
arr2 = array + index + jump;
if ((flow == UP && array[index] > array[index + jump]) ||
(flow == DOWN && array[index] < array[index + jump]))
{
tmp = *arr1;
*arr1 = *arr2;
*arr2 = tmp;
}
}
bitonic_merge(array, size, start, jump, flow);
bitonic_merge(array, size, start + jump, jump, flow);
}
}