Skip to content

Commit 94f0cdf

Browse files
authored
Merge pull request deutranium#68 from Heniboj/master
countingSort in C
2 parents 3eab606 + 8465b3d commit 94f0cdf

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
3+
int main() {
4+
int arrayLength;
5+
printf("How many numbers do you want to sort? ");
6+
scanf("%d",&arrayLength);
7+
int array[arrayLength];
8+
int sortedArray[arrayLength];
9+
int largest = 0;
10+
for (int i = 0; i < arrayLength; i++) {
11+
printf("%d. number:",i+1);
12+
int j;
13+
scanf("%d", &j);
14+
if (j > largest) {
15+
largest = j;
16+
}
17+
array[i] = j;
18+
}
19+
int count[largest+1];
20+
for(int i = 0; i < largest+1; i++) {
21+
count[i] = 0;
22+
}
23+
for(int i = 0; i < arrayLength; i++) {
24+
count[array[i]]++;
25+
}
26+
for(int i = 1; i < largest+1; i++) {
27+
count[i] += count[i-1];
28+
}
29+
for(int i = 0; i < arrayLength; i++) {
30+
sortedArray[count[array[i]]-1] = array[i];
31+
count[array[i]] -= 1;
32+
}
33+
printf("\nSorted array: ");
34+
for(int i = 0; i < arrayLength; i++) {
35+
printf("%d ",sortedArray[i]);
36+
}
37+
return 0;
38+
}

0 commit comments

Comments
 (0)