-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102-counting_sort.c
More file actions
71 lines (61 loc) · 1.34 KB
/
102-counting_sort.c
File metadata and controls
71 lines (61 loc) · 1.34 KB
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
#include "sort.h"
/**
* get_max - Returns the maximum number
*
* @array: The array to be tranversed
* @size: The array size
*
* Return: (int) the largest value in the array
*/
int get_max(int *array, size_t size)
{
size_t i;
int max = array[0];
for (i = 0; i < size; i++)
{
if (array[i] > max)
max = array[i];
}
return (max);
}
/**
* counting_sort - sorts an array of integers in ascending order using
* the Counting sort algorithm
*
* @array: The array to be sorted
* @size: The array size
*/
void counting_sort(int *array, size_t size)
{
int *count;
int *output;
int max;
long i;
if (array == NULL || size <= 1)
return;
max = get_max(array, size);
count = malloc(sizeof(int) * (max + 1));
output = malloc(sizeof(int) * (size + 1));
if (output == NULL || count == NULL)
return;
for (i = 0; i < max; i++)
count[i] = 0;
/* store count for each element */
for (i = 0; i < (long)size; i++)
count[array[i]]++;
/* find cummulative frequency */
for (i = 1; i <= max; i++)
count[i] += count[i - 1];
print_array(count, max + 1);
/* find index of each element in input and place in output */
for (i = size - 1; i >= 0; i--)
{
output[count[array[i]] - 1] = array[i];
count[array[i]]--;
}
/* store sorted elements in the array */
for (i = 0; i < (long)size; i++)
array[i] = output[i];
free(count);
free(output);
}