-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path105-radix_sort.c
81 lines (62 loc) · 1.17 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
#include "sort.h"
#include <stdlib.h>
/**
* max_max - max.
* @array: array.
* @size: size.
* Return: max.
*/
int max_max(int *array, int size)
{
int max, i;
for (max = array[0], i = 1; i < size; i++)
{
if (array[i] > max)
max = array[i];
}
return (max);
}
/**
* counting - count.
* @array: array.
* @size: size.
* @sig: sig.
* @buff: buffer.
*/
void counting(int *array, size_t size, int sig, int *buff)
{
int count[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
size_t i;
for (i = 0; i < size; i++)
count[(array[i] / sig) % 10] += 1;
for (i = 0; i < 10; i++)
count[i] += count[i - 1];
for (i = size - 1; (int)i >= 0; i--)
{
buff[count[(array[i] / sig) % 10] - 1] = array[i];
count[(array[i] / sig) % 10] -= 1;
}
for (i = 0; i < size; i++)
array[i] = buff[i];
}
/**
* radix_sort -sort.
* @array: array.
* @size: size.
*/
void radix_sort(int *array, size_t size)
{
int max, sig, *buff;
if (array == NULL || size < 2)
return;
buff = malloc(sizeof(int) * size);
if (buff == NULL)
return;
max = max_max(array, size);
for (sig = 1; max / sig > 0; sig *= 10)
{
counting(array, size, sig, buff);
print_array(array, size);
}
free(buff);
}