【发布时间】:2016-03-23 12:22:44
【问题描述】:
我正在尝试理解基数排序。特别是,我无法理解 radixing 函数——更具体地说,是 j 和 k 循环。我不确定到底发生了什么。从我所见,似乎 j 循环正在为 k 循环设置索引以用于形成已排序的输出数组。如果有人可以帮助解释其背后的逻辑,那就太好了!
// RADIX SORT BEGIN //
// Get the maximum value in arr[]
int getMax(int arr[], int size)
{
int max = arr[0]; // Set max to presumably the first one
int i = 1;
while (i < size)
{
if (arr[i] > max) // We have a new max ladies and gents
max = arr[i];
i++;
}
return max;
}
// Do a sort of arr[] based off the digit represented by exp
void radixing(int arr[], int size, int exponent)
{
int output[size];
int count[10] = {0};
// Tally the amount of numbers whose LSB based off current exponent
// is 0-9, represented by each
// index in the array
for (int i = 0; i < size; i++)
count[ (arr[i]/exponent) % 10 ]++;
for (int j = 1; j < 10; j++)
count[ j ] += count [j - 1];
for (int k = size - 1; k >= 0; k--)
{
output[ count[ (arr[k]/exponent) % 10 ] -1 ] = arr[k];
count[ (arr[k]/exponent) % 10 ]--;
}
// Finalize output into the original array
for (int o = 0; o < size; o++)
arr[o] = output[o];
}
// Main radix sort function
void radixsort(int arr[], int size)
{
// Find the max in the array to know the number of digits to traverse
int max = getMax(arr, size);
// Begin radixing by sorting the arr[] based off every digit until max
// Exponent is 10^i where i starts at 0, the current digit number
for (int exponent = 1; (max / exponent) > 0; exponent = exponent * 10)
radixing(arr, size, exponent);
}
// RADIX SORT END //
【问题讨论】:
-
您在 Google 上搜索过“基数排序”吗?只有几千条结果,包括关于该主题的维基百科文章、YouTube 视频和 CS 讲座材料。
-
@JonathonReinhart 维基百科不具有权威性。
-
@nicomp 来自 Stack Overflow 上的一些笨蛋的回答是?
-
@Jonathon Reinhart,如果这个 schmuck 得分很高,我想说相对于匿名帖子,我们有点权威。
标签: c++ sorting radix-sort