-
Notifications
You must be signed in to change notification settings - Fork 381
/
BucketSort.cpp
69 lines (61 loc) · 1.09 KB
/
BucketSort.cpp
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
62
63
64
65
66
67
68
69
#include <cstdio>
#include <climits>
#define INF INT_MAX
#define ELEMENT_COUNT 100000
#define ELEMENT_RANGE (1 << 17)
#define GROUP_RANGE (1 << 2)
using namespace std;
int n, d[ELEMENT_COUNT];
struct node
{
int v, next;
}A[ELEMENT_COUNT + 1];
int head[ELEMENT_RANGE / GROUP_RANGE], cnt[ELEMENT_RANGE / GROUP_RANGE], vc = 1;
void insert(int v)
{
int group = v / GROUP_RANGE;
A[vc].next = head[group];
head[group] = vc;
A[vc].v = v;
cnt[group]++;
vc++;
}
void bucket_sort()
{
for (int i = 0; i < n; i++)
{
insert(d[i]);
}
int ptr = 0;
for (int i = 0; i < ELEMENT_RANGE / GROUP_RANGE; i++)
{
for (int j = 0; j < cnt[i]; j++)
{
int minv = INF, ord;
for (int cur = head[i]; cur != 0; cur = A[cur].next)
{
if (A[cur].v < minv)
{
minv = A[cur].v;
ord = cur;
}
}
d[ptr++] = minv;
A[ord].v = INF;
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &d[i]);
}
bucket_sort();
for (int i = 0; i < n; i++)
{
printf("%d ", d[i]);
}
return 0;
}