-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathcounting_sort.c
69 lines (61 loc) · 1.54 KB
/
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
/*
* Date: 2017-11-29
*
* Description:
* Implement counting sort.
*
* Approach:
* This works for integer only and sorts in O(n) if we know the range of input
* elements is from 0 to k.
*
* Problem:
* As k increases and dominates over n, both time and space complexity
* increases. Like if k = n^2 then complexity of this algorithm becomes O(n^2).
* In such cases radix sort can be used.
*
* Reference:
* https://www.hackerearth.com/practice/algorithms/sorting/counting-sort/tutorial/
*
* Complexity:
* Time - O(n + k)
* Space - O(k)
*/
#include "stdio.h"
#include "stdlib.h"
void print_array(int arr[], int n, char *msg) {
int i = 0;
printf("*********** %s *****************\n", msg);
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n\n");
}
int main() {
int i = 0, j = 0, l = 0;
int n = 0;
int *a = NULL, *count = NULL;
int k = 0;
printf("Enter range of elements: ");
scanf("%d", &k);
k += 1; // +1 to accommodate 0 to k.
count = (int *)malloc(sizeof(int) * k);
// Set count to 0 for each element.
for (i = 0; i < k; i++)
count[i] = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int) * n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d", &a[i]);
// Take count of each element.
count[a[i]]++;
}
print_array(a, n, "Inserted Array");
// Update array as per counts of each element.
for (i = 0; i < k; i++) {
for (j = 0; j < count[i]; j++)
a[l++] = i;
}
print_array(a, n, "Sorted Array");
return 0;
}