-
Notifications
You must be signed in to change notification settings - Fork 0
/
105-radix_sort.c
101 lines (90 loc) · 1.81 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdlib.h>
#include "sort.h"
/**
* csort2 - auxiliary function of radix sort
*
* @array: array of data to be sorted
* @buff: malloc buffer
* @size: size of data
* @lsd: Less significant digit
*
* Return: No Return
*/
void csort2(int *array, int **buff, int size, int lsd)
{
int i, j, csize = 10, num;
int carr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int carr2[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (i = 0; i < size; i++)
{
num = array[i];
for (j = 0; j < lsd; j++)
if (j > 0)
num = num / 10;
num = num % 10;
buff[num][carr[num]] = array[i];
carr[num] += 1;
}
for (i = 0, j = 0; i < csize; i++)
{
while (carr[i] > 0)
{
array[j] = buff[i][carr2[i]];
carr2[i] += 1, carr[i] -= 1;
j++;
}
}
print_array(array, size);
}
/**
* csort - auxiliary function of radix sort
*
* @array: array of data to be sorted
* @size: size of data
* @lsd: Less significant digit
*
* Return: No Return
*/
void csort(int *array, int size, int lsd)
{
int carr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int i, j, num, csize = 10, **buff;
for (i = 0; i < size; i++)
{
num = array[i];
for (j = 0; j < lsd; j++)
if (j > 0)
num = num / 10;
num = num % 10;
carr[num] += 1;
}
if (carr[0] == size)
return;
buff = malloc(sizeof(int *) * 10);
if (!buff)
return;
for (i = 0; i < csize; i++)
if (carr[i] != 0)
buff[i] = malloc(sizeof(int) * carr[i]);
csort2(array, buff, size, lsd);
csort(array, size, lsd + 1);
for (i = 0; i < csize; i++)
if (carr[i] > 0)
free(buff[i]);
free(buff);
}
/**
* radix_sort - sorts an array of integers in ascending order using the Radix
* sort algorithm
*
* @array: array of data to be sorted
* @size: size of data
*
* Return: No Return
*/
void radix_sort(int *array, size_t size)
{
if (size < 2)
return;
csort(array, size, 1);
}