I have been trying to understand this code for hours unsuccessfully. I wrote my own version of bead sort algorithm however it is so slow.
I want to understand why this one works so much more quickly.
Here’s info about the bead sort algorithm:
http://demonstrations.wolfram.com/ExtendedBeadSort/
Can you please help me to understand how this algorithm works?
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
//*beads* go down into different buckets using gravity (addition).
if (dist > List.size() )
List.resize(dist); //resize if too big for current vector
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth (myints, myints + n);
cout << "sakums\n";
cout << myints<< "\n";
// for (vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) cout << " " << *it << "\n";
cout << "beigas\n";
cout << "#1 Beads falling down: ";
for (int i=0; i < fifth.size(); i++)
distribute (fifth[i], list);
cout << '\n';
cout << "\nBeads on their sides: ";
for (int i=0; i < list.size(); i++)
cout << " " << list[i];
cout << '\n';
//second part
cout << "#2 Beads right side up: ";
for (int i=0; i < list.size(); i++)
distribute (list[i], list2);
cout << '\n';
return list2;
}
int main() {
int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
cout << "Sorted list/array";
for(unsigned int i=0; i<sorted.size(); i++)
cout << sorted[i] << ' ';
system("PAUSE");
return 0;
}
Because of how distribute works:
Each of the other numbers contribute “beads” to the slots – there are 13 numbers so slot 1 has 13 in it when it finishes the first pass.
it “distributes” beads in “columns” I.e when you print it on its side, there are now 734 slots – the largest number.
When distribute runs again it shifts the “beads” down by summing the columns – it will perform a number of additions dependent on the max element * The number of numbers – plus memory allocations