-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
bead_sort.cpp
56 lines (44 loc) · 1.3 KB
/
bead_sort.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
// C++ program to implement gravity/bead sort
#include <cstdio>
#include <cstring>
#define BEAD(i, j) beads[i * max + j]
// function to perform the above algorithm
void beadSort(int *a, int len) {
// Find the maximum element
int max = a[0];
for (int i = 1; i < len; i++)
if (a[i] > max)
max = a[i];
// allocating memory
unsigned char *beads = new unsigned char[max * len];
memset(beads, 0, static_cast<size_t>(max) * len);
// mark the beads
for (int i = 0; i < len; i++)
for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1;
for (int j = 0; j < max; j++) {
// count how many beads are on each post
int sum = 0;
for (int i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
// Move beads down
for (int i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
// Put sorted values in array using beads
for (int i = 0; i < len; i++) {
int j;
for (j = 0; j < max && BEAD(i, j); j++) {
}
a[i] = j;
}
delete[] beads;
}
// driver function to test the algorithm
int main() {
int a[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(a) / sizeof(a[0]);
beadSort(a, len);
for (int i = 0; i < len; i++) printf("%d ", a[i]);
return 0;
}