Skip to content

Commit 9b0d630

Browse files
Write a function that sorts an array of integers in ascending order using the Radix sort algorithm. Prototype: void radix_sort(int *array, size_t size); You must implement the LSD radix sort algorithm.
1 parent d46b198 commit 9b0d630

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

105-radix_sort.c

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include "sort.h"
2+
/**
3+
* pow_10 - calculates a positive power of 10
4+
* @power: power of 10 to calculate
5+
* Return: final result
6+
*/
7+
unsigned int pow_10(unsigned int power)
8+
{
9+
unsigned int i, res;
10+
11+
res = 1;
12+
for (i = 0; i < power; i++)
13+
res *= 10;
14+
return (res);
15+
}
16+
17+
/**
18+
* count_sort - sorts an array of integers in ascending order
19+
* @array: array to be sorted
20+
* @size: size of the array to be sorted
21+
* @digit: digit to sort
22+
*
23+
* Return: 1 if when need to keep sorting, otherwise 0
24+
*/
25+
unsigned int count_sort(int *array, size_t size, unsigned int digit)
26+
{
27+
int i, count[10] = {0};
28+
int *cpy = NULL;
29+
size_t j, temp, total = 0;
30+
unsigned int dp1, dp2, sort = 0;
31+
32+
dp2 = pow_10(digit - 1);
33+
dp1 = dp2 * 10;
34+
cpy = malloc(sizeof(int) * size);
35+
if (cpy == NULL)
36+
exit(1);
37+
for (j = 0; j < size; j++)
38+
{
39+
cpy[j] = array[j];
40+
if (array[j] / dp1 != 0)
41+
sort = 1;
42+
}
43+
for (i = 0; i < 10 ; i++)
44+
count[i] = 0;
45+
for (j = 0; j < size; j++)
46+
count[(array[j] % dp1) / dp2] += 1;
47+
for (i = 0; i < 10; i++)
48+
{
49+
temp = count[i];
50+
count[i] = total;
51+
total += temp;
52+
}
53+
for (j = 0; j < size; j++)
54+
{
55+
array[count[(cpy[j] % dp1) / dp2]] = cpy[j];
56+
count[(cpy[j] % dp1) / dp2] += 1;
57+
}
58+
free(cpy);
59+
return (sort);
60+
}
61+
62+
/**
63+
* radix_sort - Radix sort algorithm
64+
* @array: array to sort
65+
* @size: size of the array
66+
*/
67+
void radix_sort(int *array, size_t size)
68+
{
69+
unsigned int i, sort = 1;
70+
71+
if (array == NULL || size < 2)
72+
return;
73+
for (i = 1; sort == 1; i++)
74+
{
75+
sort = count_sort(array, size, i);
76+
print_array(array, size);
77+
}
78+
}

0 commit comments

Comments
 (0)