-
Notifications
You must be signed in to change notification settings - Fork 3
/
102-counting_sort.c
54 lines (51 loc) · 994 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
#include "sort.h"
#include "stdlib.h"
/**
* counting_sort - sorts an array of integers in ascending order using the
* Counting sort algorithm
* @array: array to sort
* @size: size of the array to sort
*
* Return: void
*/
void counting_sort(int *array, size_t size)
{
int i, max;
int *count = NULL, *copy = NULL;
size_t j, temp, total = 0;
if (array == NULL || size < 2)
return;
copy = malloc(sizeof(int) * size);
if (copy == NULL)
return;
for (j = 0, max = 0; j < size; j++)
{
copy[j] = array[j];
if (array[j] > max)
max = array[j];
}
count = malloc(sizeof(int) * (max + 1));
if (count == NULL)
{
free(copy);
return;
}
for (i = 0; i <= max; i++)
count[i] = 0;
for (j = 0; j < size; j++)
count[array[j]] += 1;
for (i = 0; i <= max; i++)
{
temp = count[i];
count[i] = total;
total += temp;
}
for (j = 0; j < size; j++)
{
array[count[copy[j]]] = copy[j];
count[copy[j]] += 1;
}
print_array(count, max + 1);
free(count);
free(copy);
}