-
Notifications
You must be signed in to change notification settings - Fork 3
/
105-radix_sort.c
85 lines (79 loc) · 1.69 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
79
80
81
82
83
84
85
#include "sort.h"
#include <stdlib.h>
/**
* pow_10 - calculates a positive power of 10
* @power: power of 10 to calculate
*
* Return: the corresponding power of 10
*/
unsigned int pow_10(unsigned int power)
{
unsigned int i, result;
result = 1;
for (i = 0; i < power; i++)
result *= 10;
return (result);
}
/**
* count_sort - sorts an array of integers in ascending order at a specific
* digit location using the Counting sort algorithm
* @array: array to sort
* @size: size of the array to sort
* @digit: digit to sort by
*
* Return: 1 if there is a need to keep sorting, 0 if not
*/
unsigned int count_sort(int *array, size_t size, unsigned int digit)
{
int i, count[10] = {0};
int *copy = NULL;
size_t j, temp, total = 0;
unsigned int dp1, dp2, sort = 0;
dp2 = pow_10(digit - 1);
dp1 = dp2 * 10;
copy = malloc(sizeof(int) * size);
if (copy == NULL)
exit(1);
for (j = 0; j < size; j++)
{
copy[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[(copy[j] % dp1) / dp2]] = copy[j];
count[(copy[j] % dp1) / dp2] += 1;
}
free(copy);
return (sort);
}
/**
* radix_sort - sorts an array of integers in ascending order using
* the Radix sort algorithm
* @array: array to sort
* @size: size of the array
*
* Return: void
*/
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);
}
}