-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-counting_sort.c
60 lines (57 loc) · 1.37 KB
/
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
#include "sort.h"
#include <stdio.h>
/**
*_calloc - this is a calloc function
*@nmemb: number of elemets
*@size: bit size of each element
*Return: pointer to memory assignement
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
unsigned int i = 0;
char *p;
if (nmemb == 0 || size == 0)
return ('\0');
p = malloc(nmemb * size);
if (p == '\0')
return ('\0');
for (i = 0; i < (nmemb * size); i++)
p[i] = '\0';
return (p);
}
/**
* counting_sort - this is a counting sort method implementation
* @array: array to sort
* @size: array size
*/
void counting_sort(int *array, size_t size)
{
int index, maximun = 0, *counter = '\0', *tmp = '\0';
size_t i;
if (array == '\0' || size < 2)
return;
/* find maximun number */
for (i = 0; i < size; i++)
if (array[i] > maximun)
maximun = array[i];
counter = _calloc(maximun + 1, sizeof(int));
tmp = _calloc(size + 1, sizeof(int));
/* count the array elements */
for (i = 0; i < size; i++)
counter[array[i]]++;
/* get the accumulative values */
for (index = 1; index <= maximun; index++)
counter[index] += counter[index - 1];
print_array(counter, maximun + 1);
/* get the new array sorted */
for (i = 0; i < size; ++i)
{
tmp[counter[array[i]] - 1] = array[i];
counter[array[i]]--;
}
/* replace old array to new array sorted */
for (i = 0; i < size; i++)
array[i] = tmp[i];
free(tmp);
free(counter);
}