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