Skip to content

Commit 773eb9e

Browse files
Write a function that sorts an array of integers in ascending order using the Bitonic sort algorithm. Prototype: void bitonic_sort(int *array, size_t size); You can assume that size will be equal to 2^k, where k >= 0 (when array is not NULL …). You are allowed to use printf
1 parent 9b0d630 commit 773eb9e

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

106-bitonic_sort.c

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include "sort.h"
2+
/**
3+
* bitonic_compare - sort bitonic algorithm
4+
* @up: direction of sorting
5+
* @array: sub-array to sort
6+
* @size: size of the sub-array
7+
*/
8+
void bitonic_compare(char up, int *array, size_t size)
9+
{
10+
size_t i, eva;
11+
int swap;
12+
13+
eva = size / 2;
14+
for (i = 0; i < eva; i++)
15+
{
16+
if ((array[i] > array[i + eva]) == up)
17+
{
18+
swap = array[i];
19+
array[i] = array[i + eva];
20+
array[i + eva] = swap;
21+
}
22+
}
23+
}
24+
25+
/**
26+
* bitonic_merge - recursion to mergess ub-arrays
27+
* @up: direction of sorting
28+
* @array: sub-array to sort
29+
* @size: size of the sub-array
30+
*
31+
* Return: void
32+
*/
33+
void bitonic_merge(char up, int *array, size_t size)
34+
{
35+
if (size < 2)
36+
return;
37+
bitonic_compare(up, array, size);
38+
bitonic_merge(up, array, size / 2);
39+
bitonic_merge(up, array + (size / 2), size / 2);
40+
}
41+
42+
/**
43+
* bit_sort - recursive bitonic sort algorithm
44+
* @up: direction of sorting
45+
* @array: sub-array to sort
46+
* @size: size of the sub-array
47+
* @t: total size of the original array
48+
*
49+
* Return: void
50+
*/
51+
void bit_sort(char up, int *array, size_t size, size_t t)
52+
{
53+
if (size < 2)
54+
return;
55+
printf("Merging [%lu/%lu] (%s):\n", size, t, (up == 1) ? "UP" : "DOWN");
56+
print_array(array, size);
57+
bit_sort(1, array, size / 2, t);
58+
bit_sort(0, array + (size / 2), size / 2, t);
59+
bitonic_merge(up, array, size);
60+
printf("Result [%lu/%lu] (%s):\n", size, t, (up == 1) ? "UP" : "DOWN");
61+
print_array(array, size);
62+
63+
}
64+
65+
/**
66+
* bitonic_sort - sorts an array in ascending order
67+
* @array: array to sort
68+
* @size: size of the array
69+
*
70+
* Return: void
71+
*/
72+
void bitonic_sort(int *array, size_t size)
73+
{
74+
if (array == NULL || size < 2)
75+
return;
76+
bit_sort(1, array, size, size);
77+
}

0 commit comments

Comments
 (0)