Lsd基数排序+计数排序混乱

时间:2014-03-21 20:10:54

标签: c++ algorithm sorting radix-sort

我有一个基于位的LSD基数排序工作,但我很困惑我必须做的事情才能让它工作。在我的LSD_radixsort函数中,r是我用bit =(2 ^ r)-1表示的最大位。我的for循环然后经过bit / exp>但是,当我将位作为int类型时,它并没有完全对我的数组进行排序。当我把它变成双重的时候,就会对整个事情进行排序。如果我处理小数,那么循环永远不会破坏,因为它总是会有一些大于0的小数字?这是我的代码:

#include "lab8.h"
#include <iostream>
using namespace std;

void countSort2(unsigned int arr[], int n, int exp);
unsigned int getMax(unsigned int arr[], int n);

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


    // Find the maximum number to know number of digits

    double bits = pow(2,r)-1;


    // Do counting sort for every digit.

    for (int exp = 1; bits/exp > 0; exp *= 2)
    {
        countSort2(A, size, exp);
    }


}


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



    // Store count of occurrences in count[]

    for (i = 0; i < n; i++)
        count[ (arr[i]/exp)%2 ]++; 

    // Change count[i] so that count[i] now contains actual position of
    // this digit in output[]

    for (i = 1; i < 2; i++)
        count[i] += count[i - 1];

    // Build the output array

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

    // 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];


}


int main()
{
    unsigned int b[10] = {43,351,25,24,52,65,43,1,4,9};
    LSD_radixSort(b,10,5);
    int i = 0;
    while(i<10)
    {
        cout<<b[i]<<endl;
        i++;
    }
    system("pause");

}

当我用双位运行它时,我的输出数组= 1,4,9,24,25,43,43,52,65,351

当我用int位运行它时,我的输出数组= 65,1,4,9,43,43,52,24,25,351

有关为何发生这种情况的任何想法?难道我不希望我的类型是int?

0 个答案:

没有答案