几个小时以来,我一直试图理解这段代码,但没有成功。我编写了自己的珠子排序算法版本,但是速度太慢了。我想了解为什么这个工作得这么快。这里是关于珠排序算法的信息:
http
://demonstrations.wolfram.com/ExtendedBeadSort/
你能帮我理解这个算法是如何工作的吗?
#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;
}