-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102-counting_sort.c
executable file
·70 lines (58 loc) · 1.31 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
#include "sort.h"
/**
* get_max - Gets the maximum value in an array of integers
* @array: Array of integers
* @size: Array size
*
* Return: The maximum integer in the array.
*/
int get_max(int *array, int size)
{
int maximum, x;
for (maximum = array[0], x = 1; x < size; x++)
{
if (array[x] > maximum)
maximum = array[x];
}
return (maximum);
}
/**
* counting_sort - Sorting an array of integers in ascending order
* using the Counting Sort algorithm.
* @array: Array of integers
* @size: Array size
*
* Description: Prints the counting array after setting it up.
*/
void counting_sort(int *array, size_t size)
{
int *count, *sorted, maximum, x;
if (array == NULL || size < 2)
return;
sorted = malloc(sizeof(int) * size);
if (sorted == NULL)
return;
maximum = get_max(array, size);
count = malloc(sizeof(int) * (maximum + 1));
if (count == NULL)
{
free(sorted);
return;
}
for (x = 0; x < (maximum + 1); x++)
count[x] = 0;
for (x = 0; x < (int)size; x++)
count[array[x]] += 1;
for (x = 0; x < (maximum + 1); x++)
count[x] += count[x - 1];
print_array(count, maximum + 1);
for (x = 0; x < (int)size; x++)
{
sorted[count[array[x]] - 1] = array[x];
count[array[x]] -= 1;
}
for (x = 0; x < (int)size; x++)
array[x] = sorted[x];
free(sorted);
free(count);
}