-
Notifications
You must be signed in to change notification settings - Fork 0
/
106-bitonic_sort.c
91 lines (79 loc) · 1.71 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
#include "sort.h"
/**
* bitonic_sort - Sorts array using bitonic algo
* @array: Array to sort
* @size: Size of array
*/
void bitonic_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
b_sort(array, 0, size, 1, size);
}
/**
* b_merge - bitonic merge
* @array: Array slice being merged
* @low: lowest index
* @count: Count of slice
* @dir: Direction, ascending 1 descending 0
* @size: size of total array for printing
*/
void b_merge(int *array, int low, int count, int dir, size_t size)
{
int i, n;
if (count > 1)
{
n = count / 2;
for (i = low; i < low + n; i++)
{
if (((array[i] > array[i + n]) && dir == 1) ||
(dir == 0 && (array[i] < array[i + n])))
swap(&array[i], &array[i + n]);
}
b_merge(array, low, n, dir, size);
b_merge(array, low + n, n, dir, size);
}
}
/**
* b_sort - bitonic recursive sort
* @array: array to sort
* @low: lowest index
* @count: Count of slice
* @dir: Direction, ascending 1 descending 0
* @size: size of total array for printing
*/
void b_sort(int *array, int low, int count, int dir, size_t size)
{
int n;
if (count > 1)
{
n = count / 2;
printf("Merging [%d/%d] ", count, (int)size);
if (dir == 1)
printf("(UP):\n");
else
printf("(DOWN):\n");
print_array(array + low, count);
b_sort(array, low, n, 1, size);
b_sort(array, low + n, n, 0, size);
b_merge(array, low, count, dir, size);
printf("Result [%d/%d] ", count, (int)size);
if (dir == 1)
printf("(UP):\n");
else
printf("(DOWN):\n");
print_array(array + low, count);
}
}
/**
* swap - Swap two integers in an array.
* @a: Thj first integer to swap.
* @b: The second integer to swap.
*/
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}