-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounting_sort.c
61 lines (50 loc) · 958 Bytes
/
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
#include <stdio.h>
void printArray(int *arr, int n)
{
int i;
for(i=0; i<n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
void countingSort(int *A, int n)
{
int i;
/* Find max */
int max = 0;
for(i=1; i<n; i++){
if(A[i]>A[i-1])
max = A[i];
}
// Init count array
int count[max+1];
for(i=0; i<max+1; i++){
count[i] = 0;
}
/* Count number of occurence */
for(i=0; i<n; i++){
count[A[i]] += 1;
}
/* Prefix sum */
for(i=1; i<max+1; i++){
count[i] += count[i-1];
}
/* Fill sorted array */
int B[n];
for(i=n-1; i>=0; i--){
B[--count[A[i]]] = A[i];
}
/* Replace array */
for(i=0; i<n; i++){
A[i] = B[i];
}
}
int main()
{
int arr[5] = {10,4,11,5,3};
int n = sizeof(arr)/sizeof(arr[0]);
printArray(arr, n);
countingSort(arr, n);
printArray(arr, n);
return 0;
}