-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path102-counting_sort.c
75 lines (54 loc) · 941 Bytes
/
102-counting_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
#include "sort.h"
#include <limits.h>
#include <stdlib.h>
/**
* get_max - max
*
* @array: array
* @size: size
* Return: 0
*/
int get_max(int *array, size_t size)
{
int max = INT_MIN;
while (size--)
if (array[size] > max)
max = array[size];
return (max);
}
/**
* counting_sort - sort.
* @array: array
* @size: size.
*/
void counting_sort(int *array, size_t size)
{
int *temp, *cpy, j, max;
size_t i;
if (!array || size < 2)
return;
max = get_max(array, size);
temp = calloc(max + 1, sizeof(*temp));
if (!temp)
return;
cpy = malloc(sizeof(*cpy) * size);
if (!cpy)
{
free(temp);
return;
}
for (i = 0; i < size; i++)
temp[array[i]]++;
for (j = 1; j < max + 1; j++)
temp[j] += temp[j - 1];
print_array(temp, max + 1);
for (i = 0; i < size; i++)
{
temp[array[i]]--;
cpy[temp[array[i]]] = array[i];
}
for (i = 0; i < size; i++)
array[i] = cpy[i];
free(temp);
free(cpy);
}