Skip to content

Commit 9c737f2

Browse files
Write a function that sorts an array of integers in ascending order using the Counting sort algorithm
1 parent 089dc66 commit 9c737f2

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

102-O

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
O(n+k)
2+
O(n+k)
3+
O(n+k)

102-counting_sort.c

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include "sort.h"
2+
3+
/**
4+
* get_max - Get the maximum value in an array of integers.
5+
* @array: An array of integers.
6+
* @size: The size of the array.
7+
*
8+
* Return: The maximum integer in the array.
9+
*/
10+
int get_max(int *array, int size)
11+
{
12+
int max, i;
13+
14+
for (max = array[0], i = 1; i < size; i++)
15+
{
16+
if (array[i] > max)
17+
max = array[i];
18+
}
19+
20+
return (max);
21+
}
22+
23+
/**
24+
* counting_sort - Sort an array of integers in ascending order
25+
* using the counting sort algorithm.
26+
* @array: An array of integers.
27+
* @size: The size of the array.
28+
*
29+
* Description: Prints the counting array after setting it up.
30+
*/
31+
void counting_sort(int *array, size_t size)
32+
{
33+
int *count, *sorted, max, i;
34+
35+
if (array == NULL || size < 2)
36+
return;
37+
38+
sorted = malloc(sizeof(int) * size);
39+
if (sorted == NULL)
40+
return;
41+
max = get_max(array, size);
42+
count = malloc(sizeof(int) * (max + 1));
43+
if (count == NULL)
44+
{
45+
free(sorted);
46+
return;
47+
}
48+
49+
for (i = 0; i < (max + 1); i++)
50+
count[i] = 0;
51+
for (i = 0; i < (int)size; i++)
52+
count[array[i]] += 1;
53+
for (i = 0; i < (max + 1); i++)
54+
count[i] += count[i - 1];
55+
print_array(count, max + 1);
56+
57+
for (i = 0; i < (int)size; i++)
58+
{
59+
sorted[count[array[i]] - 1] = array[i];
60+
count[array[i]] -= 1;
61+
}
62+
63+
for (i = 0; i < (int)size; i++)
64+
array[i] = sorted[i];
65+
66+
free(sorted);
67+
free(count);
68+
}

0 commit comments

Comments
 (0)