-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105-radix_sort.c
executable file
·78 lines (73 loc) · 1.48 KB
/
105-radix_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
#include "sort.h"
/**
* pow_10 - calculates a positive power of 10
* @power: power of 10 to calculate
* Return: final result
*/
unsigned int pow_10(unsigned int power)
{
unsigned int i, res;
res = 1;
for (i = 0; i < power; i++)
res *= 10;
return (res);
}
/**
* count_sort - sorts an array of integers in ascending order
* @array: array to be sorted
* @size: size of the array to be sorted
* @digit: digit to sort
*
* Return: 1 if when need to keep sorting, otherwise 0
*/
unsigned int count_sort(int *array, size_t size, unsigned int digit)
{
int i, count[10] = {0};
int *cpy = NULL;
size_t j, temp, total = 0;
unsigned int dp1, dp2, sort = 0;
dp2 = pow_10(digit - 1);
dp1 = dp2 * 10;
cpy = malloc(sizeof(int) * size);
if (cpy == NULL)
exit(1);
for (j = 0; j < size; j++)
{
cpy[j] = array[j];
if (array[j] / dp1 != 0)
sort = 1;
}
for (i = 0; i < 10 ; i++)
count[i] = 0;
for (j = 0; j < size; j++)
count[(array[j] % dp1) / dp2] += 1;
for (i = 0; i < 10; i++)
{
temp = count[i];
count[i] = total;
total += temp;
}
for (j = 0; j < size; j++)
{
array[count[(cpy[j] % dp1) / dp2]] = cpy[j];
count[(cpy[j] % dp1) / dp2] += 1;
}
free(cpy);
return (sort);
}
/**
* radix_sort - Radix sort algorithm
* @array: array to sort
* @size: size of the array
*/
void radix_sort(int *array, size_t size)
{
unsigned int i, sort = 1;
if (array == NULL || size < 2)
return;
for (i = 1; sort == 1; i++)
{
sort = count_sort(array, size, i);
print_array(array, size);
}
}