TheAlgorithms-C-Plus-Plus/sorting/bead_sort.cpp

63 lines
1.3 KiB
C++
Raw Normal View History

2020-05-26 23:33:57 +08:00
// 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)
{
2020-05-26 23:33:57 +08:00
// Find the maximum element
int max = a[0];
for (int i = 1; i < len; i++)
if (a[i] > max)
max = a[i];
2020-05-26 23:33:57 +08:00
// allocating memory
2020-05-26 23:46:24 +08:00
unsigned char *beads = new unsigned char[max * len];
memset(beads, 0, max * len);
2020-05-26 23:33:57 +08:00
// 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++)
{
2020-05-26 23:33:57 +08:00
// count how many beads are on each post
int sum = 0;
for (int i = 0; i < len; i++)
{
2020-05-26 23:33:57 +08:00
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++)
{
2020-05-26 23:33:57 +08:00
int j;
for (j = 0; j < max && BEAD(i, j); j++)
{
2020-05-27 00:15:12 +08:00
}
2020-05-26 23:33:57 +08:00
a[i] = j;
}
2020-05-26 23:46:24 +08:00
delete[] beads;
2020-05-26 23:33:57 +08:00
}
// driver function to test the algorithm
int main()
{
2020-05-26 23:33:57 +08:00
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;
}