-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102-counting_sort.c
More file actions
executable file
·64 lines (56 loc) · 1.4 KB
/
102-counting_sort.c
File metadata and controls
executable file
·64 lines (56 loc) · 1.4 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
#include "sort.h"
/**
* get_max - Get the maximum value in an array of integers.
* @array: An array of integers.
* @size: The size of the array.
*
* Return: The maximum integer in the array.
*/
int get_max(int *array, size_t size)
{
int i, max = array[0];
for (i = 1; i < (int)size; i++)
{
if (array[i] > max)
max = array[i];
}
return (max);
}
/**
* counting_sort - Afunction that sorts an array using counting algorithm.
* @array: The array to sort.
* @size: The length of the array.
* Return: Nothing.
*/
void counting_sort(int *array, size_t size)
{
int i, max;
int *count, *sorted;
if (array == NULL || size < 2)
return;
max = get_max(array, size);
sorted = malloc(sizeof(int) * size);
if (sorted == NULL)
return;
count = malloc(sizeof(int) * (max + 1));
if (count == NULL)
return;
/* intializing the array count with 0*/
for (i = 0; i < (max + 1); i++)
count[i] = 0;
/* counting the unique values of the array to be sorted */
for (i = 0; i < (int)size; i++)
count[array[i]]++;
/* summing the counts consecutively */
for (i = 1; i < (max + 1); i++)
count[i] += count[i - 1];
print_array(count, max + 1);
/* sorting the array into a sorted array*/
for (i = size - 1; i >= 0; --i)
sorted[--count[array[i]]] = array[i];
/* Reassignment of the array with the sorted array*/
for (i = 0; i < (int)size; i++)
array[i] = sorted[i];
free(sorted);
free(count);
}