小编典典

Radix Sort如何工作?

algorithm

我不知道为什么我这么难缠头。我浏览了Wiki页面和伪代码(以及实际代码),试图了解基数排序算法的工作方式(针对存储桶)。

我在这里找错东西了吗?我是否应该研究存储桶排序?有人可以给我一个简短的版本吗?作为参考,下面是一个 假定 执行基数排序的代码块:

// Sort 'size' number of integers starting at 'input' according to the 'digit'th digit
// For the parameter 'digit', 0 denotes the least significant digit and increases as significance does
void radixSort(int* input, int size, int digit)
{
    if (size == 0)
        return;

    int[10] buckets;    // assuming decimal numbers

    // Sort the array in place while keeping track of bucket starting indices.
    // If bucket[i] is meant to be empty (no numbers with i at the specified digit),
    // then let bucket[i+1] = bucket[i]

    for (int i = 0; i < 10; ++i)
    {
        radixSort(input + buckets[i], buckets[i+1] - buckets[i], digit+1);
    }
}

而且我也研究了非递归解决方案:

void radixsort(int *a, int arraySize)
{
    int i, bucket[sortsize], maxVal = 0, digitPosition =1 ;
    for(i = 0; i < arraySize; i++) {
        if(a[i] > maxVal) maxVal = a[i];
    }

    int pass = 1; 
    while(maxVal/digitPosition > 0) {
        // reset counter 
        int digitCount[10] = {0};

        // count pos-th digits (keys) 
        for(i = 0; i < arraySize; i++)
            digitCount[a[i]/digitPosition%10]++;

        // accumulated count 
        for(i = 1; i < 10; i++)
            digitCount[i] += digitCount[i-1];

        // To keep the order, start from back side
        for(i = arraySize - 1; i >= 0; i--)
            bucket[--digitCount[a[i]/digitPosition%10]] = a[i];

        for(i = 0; i < arraySize; i++)
            a[i] = bucket[i];

        cout << "pass #" << pass++ << ": ";
        digitPosition *= 10;
    }

}

具体来说,这条线给我带来麻烦。我已经尝试过用笔和纸来遍历它,但是我仍然不知道它在做什么:

   // To keep the order, start from back side
        for(i = arraySize - 1; i >= 0; i--)
            bucket[--digitCount[a[i]/digitPosition%10]] = a[i];

阅读 288

收藏
2020-07-28

共1个答案

小编典典

在数学中,基数表示基数,十进制表示基数10。想象一下,您有一些数字,其中有些数字不止一个

5, 213, 55, 21, 2334, 31, 20, 430

为简单起见,假设您要使用十进制基数(=
10)进行排序。然后,您将首先将数字分开,然后再次将它们放在一起。接下来,您将数字分开数十个,然后再次将它们放在一起;然后是数百个,依此类推,直到所有数字都被排序为止。每次循环时,只需从左至右阅读列表即可。您还可以想象您正在将数字分成多个桶。这是使用的插图5, 213, 55, 21, 2334, 31, 20, 430

按单位分开:

  • 零:20,430

  • 一个:21,31

  • 二:

  • 三分球:213

  • 四肢:2334

  • 五人制:5,55

一起返回:20、430、21、31、213、2334、5、55

要将它们放回原处,请先阅读zeroes存储桶,然后阅读存储ones桶,依此类推,直到读取nines存储桶。

分开数十:

  • 零:05

  • 一个:213

  • 二进制:20、21

  • 三分:430、31、2334,

  • 四肢:

  • 五人制:55

一起返回:5,213,20,21,430,31,2334,55

分开数百个:

  • 零:005,020,021,031,055

  • 那些:

  • 二进制:213

  • 三分球:2334

  • 四肢:430

  • 击掌

一起返回:5、20、21、31、55、213、2334、430

千位分隔:

  • 零:0005,0020,0021,0031,0055,0213,0430

  • 那些:

  • 二进制:2334

  • 三分:

  • 四肢:

  • 击掌

一起返回:5,20,21,31,55,213,430,2334

现在完成。我在Javapython的
Geekviewpoint上都看到了一个不错的代码

2020-07-28