-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102-counting_sort.c
More file actions
50 lines (39 loc) · 868 Bytes
/
102-counting_sort.c
File metadata and controls
50 lines (39 loc) · 868 Bytes
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
#include "sort.h"
/**
* counting_sort - sorts an array of integers.
* @array: The array to be sorted.
* @size: Number of elements in the array.
*/
void counting_sort(int *array, size_t size)
{
int k = 0, *count, *output, i;
if (!array || size < 2)
return;
for (i = 0; i < (int)size; i++)
if (array[i] > k)
k = array[i];
count = malloc(sizeof(int) * (k + 1));
output = malloc(sizeof(int) * size);
if (!count || !output)
{
free(count);
free(output);
return;
}
for (i = 0; i <= k; i++)
count[i] = 0;
for (i = 0; i < (int)size; i++)
count[array[i]] += 1;
for (i = 1; i <= k; i++)
count[i] += count[i - 1];
print_array(count, k + 1);
for (i = 0; i < (int)size; i++)
{
output[count[array[i]] - 1] = array[i];
count[array[i]] -= 1;
}
for (i = 0; i < (int)size; i++)
array[i] = output[i];
free(count);
free(output);
}