-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path106-bitonic_sort.c
executable file
·97 lines (82 loc) · 2.42 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
90
91
92
93
94
95
96
97
#include "sort.h"
void swapping_ints(int *a, int *b);
void bitonic_merging(int *array, size_t size, size_t start, size_t seq,
char flow);
void bitonic_sequence(int *array, size_t size, size_t start, size_t seq,
char flow);
void bitonic_sort(int *array, size_t size);
/**
* swapping_ints - Swap two integers in an array.
* @a: First integer to swap.
* @b: Second integer to swap.
*/
void swapping_ints(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/**
* bitonic_merging - Sort a bitonic sequence inside an array of integers.
* @array: Array of integers
* @size: Array size
* @start: Starting index of the sequence in array to be sorted
* @seq: Size of the sequence to be sorted
* @flow: Direction to sort in
*/
void bitonic_merging(int *array, size_t size, size_t start, size_t seq,
char flow)
{
size_t x, jump = seq / 2;
if (seq > 1)
{
for (x = start; x < start + jump; x++)
{
if ((flow == UP && array[x] > array[x + jump]) ||
(flow == DOWN && array[x] < array[x + jump]))
swapping_ints(array + x, array + x + jump);
}
bitonic_merging(array, size, start, jump, flow);
bitonic_merging(array, size, start + jump, jump, flow);
}
}
/**
* bitonic_sequence - Converting an array of integers to a bitonic sequence
* @array: Array of integers
* @size: Array size
* @start: 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_sequence(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_sequence(array, size, start, cut, UP);
bitonic_sequence(array, size, start + cut, cut, DOWN);
bitonic_merging(array, size, start, seq, flow);
printf("Result [%lu/%lu] (%s):\n", seq, size, str);
print_array(array + start, seq);
}
}
/**
* bitonic_sort - Sorting an array of integers in ascending
* order using the Bitonic sort algorithm
* @array: Array of integers
* @size: Array size
*
* Description: Printing the array after every swap.
* Only works for size = 2^k where k >= 0
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
bitonic_sequence(array, size, 0, size, UP);
}