【问题标题】:Explaining Radix Sort解释基数排序
【发布时间】: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


【解决方案1】:

我不会分解算法中的每个步骤,而是告诉你它打算完成什么,你可以用它来了解它是如何工作的。这看起来像是在做所谓的 LSD 基数排序。

如果您曾经使用过卡片分类器(现在很难找到),它的作用与此算法相同。这个想法是从最不重要的数字开始,然后朝着最大的方向努力。卡片分类器将有 10 个箱子——每个数字一个。将选择一列(指数),卡片将根据所选列的位数落入适当的箱中。

算法所做的是计算给定指数列中每个数字的记录数,然后按顺序输出那么多记录。实际上,它使用计数来计算输出数组的偏移量。

现在记录按给定列(指数)的顺序移动到下一个更高的指数。

编辑:稍加修饰。

【讨论】:

    【解决方案2】:

    j 循环将计数转换为每个桶的结束索引(1 + 索引到最后一个元素)。 k 循环根据当前数字将元素从最后一个到第一个移动到桶中。该过程从最低有效位开始,到最高有效位结束。

    另一种方法是将计数转换为起始索引,其中第一个索引 == 0,第二个索引 == 具有 '0' 位的元素的数量,...(具有 '9' 位的元素的数量没有'无关紧要且未使用)。排序的基数部分将从头到尾对元素进行排序。

    在任何一种情况下,桶的大小都是可变的,一个桶的结束是下一个桶的开始。当基数排序完成后,桶之间就没有间隙了。

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2020-08-05
      • 2015-12-01
      相关资源
      最近更新 更多