Skip to content

Commit 20945e1

Browse files
committed
Count Sort
1 parent 338a83c commit 20945e1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

sorting algo/Count/main.c

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int findMax(int A[] , int n){
5+
int max =0, i;
6+
for(i = 0 ; i< n;i++){
7+
if(A[i] > max){
8+
max = A[i];
9+
}
10+
}
11+
return max;
12+
}
13+
14+
void CountSort(int A[] , int n){
15+
int max ,i , j;
16+
int *C;
17+
18+
// find max
19+
max = findMax(A , n);
20+
// create count as the max element
21+
C = (int *)malloc(sizeof(int) *max+1);
22+
23+
// initialize count array as empty (0)
24+
for(i = 0 ; i < max+1 ; i++)
25+
C[i] = 0;
26+
27+
// store frequency/count of elements in A
28+
for(i = 0 ; i < n ; i++){
29+
C[A[i]]++;
30+
}
31+
32+
// retrieve all the elements from count by decrementing count
33+
i = 0 ,j = 0;
34+
while(i < max +1){
35+
if(C[i] > 0){
36+
A[j++] = i;
37+
C[i]--;
38+
}else {
39+
i++;
40+
}
41+
}
42+
}
43+
44+
int main()
45+
{
46+
int A[] = {11 , 3 , 10 , 15 , 5, 4 , 5 , 7 , 1 , 2} , n = 10 ,i;
47+
48+
CountSort(A , n);
49+
50+
for(i = 0 ; i<n;i++){
51+
printf("%d " ,A[i]);
52+
}
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)