Skip to content

Commit 5c1e88c

Browse files
committed
Indented "countingSort" and fixed compilation errors
Added description about advantage of counting sort over comparison sort and how counting sort can be stabilized.
1 parent 8963e54 commit 5c1e88c

File tree

1 file changed

+32
-24
lines changed

1 file changed

+32
-24
lines changed

sorting/countingSort.c

Lines changed: 32 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,36 @@
11
#include <stdio.h>
2-
int main()
3-
{
4-
int i,n,l=0;
5-
scanf("%d",&n);
6-
int a[n];
7-
for(i=0;i<n;i++)
8-
{
9-
scanf("%d",&a[i]);
10-
if(a[i]>l)
11-
l=a[i];
12-
}
13-
int b[l+1]={0};
14-
for(i=0;i<n;i++)
2+
#include<string.h>
3+
/*
4+
> Counting sort is a sorting technique based on keys between a specific range.
5+
> integer sorting algorithm
6+
> Worst-case performance O(n+k)
7+
> Stabilized by prefix sum array
8+
*/
9+
int main()
10+
{
11+
int i,n,l=0;
12+
scanf("%d",&n);
13+
int a[n];
14+
for(i=0;i<n;i++)
15+
{
16+
scanf("%d",&a[i]);
17+
if(a[i] > l)
18+
l = a[i];
19+
}
20+
int b[l+1];
21+
memset(b, 0, (l+1)*sizeof(b[0]));
22+
for(i=0;i<n;i++)
1523
b[a[i]]++; //hashing number to array index
16-
for(i=0;i<(l+1);i++)
17-
{
18-
if(b[i]>0)
24+
for(i=0;i<(l+1);i++) //unstable , stabilized by prefix sum array
1925
{
20-
while(b[i]!=0) //for case when number exists more than once
21-
{
22-
printf("%d ",i);
23-
b[i]--;
24-
}
25-
}
26+
if(b[i]>0)
27+
{
28+
while(b[i]!=0) //for case when number exists more than once
29+
{
30+
printf("%d ",i);
31+
b[i]--;
32+
}
33+
}
2634
}
27-
return 0;
28-
}
35+
return 0;
36+
}

0 commit comments

Comments
 (0)