-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcountsort.cpp
More file actions
40 lines (34 loc) · 728 Bytes
/
countsort.cpp
File metadata and controls
40 lines (34 loc) · 728 Bytes
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
#include <iostream>
using namespace std;
void countSort(int * a, int len){
int max = a[0];
for (int i = 0; i < len; i++){
if (a[i] > max){
max = a[i];
}
}
int * buffer = new int[max + 1];
for (int i = 0; i <= max; i++){
buffer[i] = 0;
}
for (int i = 0; i < len; i++){
buffer[a[i]]++;
}
int index = 0;
for (int i = 1; i <= max; i++){
if (buffer[i] > 0){
while ((buffer[i]--) > 0){
a[index++] = i;
}
}
}
}
int main(){
int a[5] = {2, 4, 2, 3, 3};
countSort(a, 5);
for (int i = 0; i < 5; i++){
cout << a[i] << " ";
}
cout << endl;
return 0;
}