-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-counting_sort.c
75 lines (61 loc) · 1.55 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "sort.h"
int get_max(int *array, int size);
/**
* counting_sort - Sorts an array of integers in ascending order using
* the Counting sort algorithm.
* @array: The array to be sorted.
* @size: The size of the array.
*
* Return: void.
*/
void counting_sort(int *array, size_t size)
{
size_t idx, max_val = 0;
int *count, *temp;
if (array == NULL || size < 2)
return;
temp = malloc(sizeof(int) * size);
if (temp == NULL)
return;
max_val = get_max(array, size); /* get max value */
count = malloc(sizeof(int) * (max_val + 1));
if (count == NULL)
{
free(temp);
return;
}
for (idx = 0; idx < max_val + 1; idx++) /* initialize array to 0 */
count[idx] = 0;
for (idx = 0; idx < size; idx++) /* counting occurences */
count[array[idx]]++;
for (idx = 1; idx <= max_val; idx++) /* cumulative sum of occurences */
count[idx] += count[idx - 1];
print_array(count, (max_val + 1));
/* sort array in reverse to maintain 'stability' */
for (idx = size - 1; (int)idx >= 0; idx--)
{
temp[count[array[idx]] - 1] = array[idx];
count[array[idx]]--;
}
for (idx = 0; idx < size; idx++)
array[idx] = temp[idx]; /* reconstruct sorted array */
free(count);
free(temp);
}
/**
* get_max - Gets the maximum value in an array of integers.
* @array: The array of integers.
* @size: The size of the array.
*
* Return: The maximum integer in the array.
*/
int get_max(int *array, int size)
{
int max, idx;
for (max = array[0], idx = 1; idx < size; idx++)
{
if (array[idx] > max)
max = array[idx];
}
return (max);
}