Jon*_*ein 5 c++ sorting algorithm bucket
我有一本书说:
a)根据值的个位数将一维数组的每个值放入桶阵列的一行中.例如,97放置在行7中,3放置在行3中,100放置在行0中.这称为"分发通道".
b)逐行循环遍历bucket数组,并将值复制回原始数组.这被称为"聚会通行证".一维数组中先前值的新顺序是100,3和97.
c)对每个后续数字位置重复此过程.
我在尝试理解和实现这一点时遇到了很多麻烦.到目前为止,我有:
void b_sort(int sarray[], int array_size) {
const int max = array_size;
for(int i = 0; i < max; ++i)
int array[i] = sarray[i];
int bucket[10][max - 1];
}
Run Code Online (Sandbox Code Playgroud)
我想,为了用数十,数百等来对它们进行排序,我可以使用它:
for(int i = 0; i < max; ++i)
insert = (array[i] / x) % 10;
bucket[insert];
Run Code Online (Sandbox Code Playgroud)
其中x = 1,10,100,1000等.我现在完全迷失了如何写这个.
这是基于OP问题中的信息的桶排序。
void b_sort(int sarray[], int array_size) {
const int max = array_size;
// use bucket[x][max] to hold the current count
int bucket[10][max+1];
// init bucket counters
for(var x=0;x<10;x++) bucket[x][max] = 0;
// main loop for each digit position
for(int digit = 1; digit <= 1000000000; digit *= 10) {
// array to bucket
for(int i = 0; i < max; i++) {
// get the digit 0-9
int dig = (sarray[i] / digit) % 10;
// add to bucket and increment count
bucket[dig][bucket[dig][max]++] = sarray[i];
}
// bucket to array
int idx = 0;
for(var x = 0; x < 10; x++) {
for(var y = 0; y < bucket[x][max]; y++) {
sarray[idx++] = bucket[x][y];
}
// reset the internal bucket counters
bucket[x][max] = 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意使用二维数组作为存储桶会浪费大量空间......队列/列表数组通常更有意义。
我通常不使用 C++ 进行编程,并且上述代码是在网络浏览器中编写的,因此可能存在语法错误。
| 归档时间: |
|
| 查看次数: |
18507 次 |
| 最近记录: |