将基于十进制的基数排序转换为基于位的排序

时间:2014-03-20 02:27:12

标签: c++ algorithm sorting

我终于让我的基于小数的基数排序工作了,但是想把它变成一个排序的东西。

void LSD_radixSort (unsigned int * A, int size, int r)
{



     // Find the maximum number to know number of digits
    int m = getMax(A, size);

    // Do counting sort for every digit. Note that instead of passing digit
    // number, exp is passed. exp is 10^i where i is current digit number
    for (int exp = 1; m/exp > 0; exp *= 10)
        countSort2(A, size, exp);


}

unsigned int getMax(unsigned int arr[], int n)
{
    unsigned int mx = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > mx)
            mx = arr[i];
    return mx;
}

void countSort2(unsigned int arr[], int n, int exp)
{
    int *output = new int[n]; // output array
    int i, count[10] = {0};

    // Store count of occurrences in count[]
    for (i = 0; i < n; i++)
        count[ (arr[i]/exp)%10 ]++; 

    // Change count[i] so that count[i] now contains actual position of
    // this digit in output[]
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];

    // Build the output array
    for (i = n - 1; i >= 0; i--)
    {
        output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
        count[ (arr[i]/exp)%10 ]--;
    }

    // Copy the output array to arr[], so that arr[] now
    // contains sorted numbers according to curent digit
    for (i = 0; i < n; i++)
        arr[i] = output[i];
     i = 0;

}

在不更改我的LSD_radixSort函数的参数的情况下,当r是我的指数2 ^ r - 1时,如何转换它?

任何建议都将非常感谢!

1 个答案:

答案 0 :(得分:0)

基本上你需要了解bitwise operators

你需要知道的基数排序是2 ^ n是1 << n,并且与bitwise和&一起你可以查询第n位是否由x & (1 << n) != 0设置