TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bead_sort.cpp
1// C++ program to implement gravity/bead sort
2#include <cstdio>
3#include <cstring>
4
5#define BEAD(i, j) beads[i * max + j]
6
7// function to perform the above algorithm
8void beadSort(int *a, int len) {
9 // Find the maximum element
10 int max = a[0];
11 for (int i = 1; i < len; i++)
12 if (a[i] > max)
13 max = a[i];
14
15 // allocating memory
16 unsigned char *beads = new unsigned char[max * len];
17 memset(beads, 0, static_cast<size_t>(max) * len);
18
19 // mark the beads
20 for (int i = 0; i < len; i++)
21 for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1;
22
23 for (int j = 0; j < max; j++) {
24 // count how many beads are on each post
25 int sum = 0;
26 for (int i = 0; i < len; i++) {
27 sum += BEAD(i, j);
28 BEAD(i, j) = 0;
29 }
30
31 // Move beads down
32 for (int i = len - sum; i < len; i++) BEAD(i, j) = 1;
33 }
34
35 // Put sorted values in array using beads
36 for (int i = 0; i < len; i++) {
37 int j;
38 for (j = 0; j < max && BEAD(i, j); j++) {
39 }
40
41 a[i] = j;
42 }
43 delete[] beads;
44}
45
46// driver function to test the algorithm
47int main() {
48 int a[] = {5, 3, 1, 7, 4, 1, 1, 20};
49 int len = sizeof(a) / sizeof(a[0]);
50
51 beadSort(a, len);
52
53 for (int i = 0; i < len; i++) printf("%d ", a[i]);
54
55 return 0;
56}
int main()
Main function.
T sum(const std::vector< std::valarray< T > > &A)