-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path102-counting_sort.c
More file actions
52 lines (44 loc) · 854 Bytes
/
102-counting_sort.c
File metadata and controls
52 lines (44 loc) · 854 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
51
52
#include "sort.h"
/**
* counting_sort -Sorts an arrayof integers
* in ascending order using the
* Counting sort algorithm
* @array: array
* @size: size
* Return: no return
*/
void counting_sort(int *array, size_t size)
{
int n, i;
int *buff, *a;
if (size < 2)
return;
for (n = i = 0; i < (int)size; i++)
if (array[i] > n)
n = array[i];
buff = malloc(sizeof(int) * (n + 1));
if (!buff)
return;
for (i = 0; i <= n; i++)
buff[i] = 0;
for (i = 0; i < (int)size; i++)
buff[array[i]] += 1;
for (i = 1; i <= n; i++)
buff[i] += buff[i - 1];
print_array(buff, (n + 1));
a = malloc(sizeof(int) * (size + 1));
if (!a)
{
free(buff);
return;
}
for (i = 0; i < (int)size; i++)
{
a[buff[array[i]] - 1] = array[i];
buff[array[i]] -= 1;
}
for (i = 0; i < (int)size; i++)
array[i] = a[i];
free(buff);
free(a);
}