首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基数排序在C++中的实现

基数排序在C++中的实现
EN

Stack Overflow用户
提问于 2009-08-13 11:21:06
回答 3查看 44.6K关注 0票数 8

我正在尝试通过创建一个程序来改进我的节点,该程序将接受1到10^6之间的大量数字。将在每次遍历中存储数字的存储桶是一个节点数组(其中C++是我创建的包含一个值和一个下一个节点属性的结构)。

根据最低有效值将数字排序到存储桶中后,我将一个存储桶的末尾指向另一个存储桶的开头(这样我就可以在不打乱顺序的情况下快速获取要存储的数字)。我的代码没有错误(无论是编译还是运行时),但我在如何解决剩下的6次迭代方面遇到了困难(因为我知道数字的范围)。

我遇到的问题是,最初数字是以整数数组的形式提供给radixSort函数的。在排序的第一次迭代之后,数字现在存储在结构数组中。有没有办法重写我的代码,让我在7次迭代中只有一个for循环,或者我需要一个for循环来运行一次,然后在它下面再运行一个循环,在返回完全排序的列表之前运行6次?

代码语言:javascript
复制
#include <iostream>
#include <math.h>
using namespace std;

struct node
{
    int value;
    node *next; 
};

//The 10 buckets to store the intermediary results of every sort
node *bucket[10];
//This serves as the array of pointers to the front of every linked list
node *ptr[10];
//This serves as the array of pointer to the end of every linked list
node *end[10];
node *linkedpointer;
node *item;
node *temp;

void append(int value, int n)
{
    node *temp; 
    item=new node;
    item->value=value;
    item->next=NULL;
    end[n]=item;
    if(bucket[n]->next==NULL)
    {
        cout << "Bucket " << n << " is empty" <<endl;
        bucket[n]->next=item;
        ptr[n]=item;
    }
    else
    {
        cout << "Bucket " << n << " is not empty" <<endl;
        temp=bucket[n];
        while(temp->next!=NULL){
            temp=temp->next;
        }
        temp->next=item;
    }
}

bool isBucketEmpty(int n){
    if(bucket[n]->next!=NULL)
        return false;
    else
        return true;
}
//print the contents of all buckets in order
void printBucket(){
    temp=bucket[0]->next;
    int i=0;
    while(i<10){
        if(temp==NULL){
            i++;
            temp=bucket[i]->next;                       
        }
        else break;

    }
    linkedpointer=temp;
    while(temp!=NULL){
        cout << temp->value <<endl;
        temp=temp->next;
    }
}

void radixSort(int *list, int length){
    int i,j,k,l;
    int x;
    for(i=0;i<10;i++){
        bucket[i]=new node;
        ptr[i]=new node;
        ptr[i]->next=NULL;
        end[i]=new node;
    }
    linkedpointer=new node;

    //Perform radix sort
    for(i=0;i<1;i++){
        for(j=0;j<length;j++){          
            x=(int)(*(list+j)/pow(10,i))%10;            
            append(*(list+j),x);
            printBucket(x); 
        }//End of insertion loop
        k=0,l=1;

        //Linking loop: Link end of one linked list to the front of another
        for(j=0;j<9;j++){
            if(isBucketEmpty(k))
                k++;
            if(isBucketEmpty(l) && l!=9)
                l++;
            if(!isBucketEmpty(k) && !isBucketEmpty(l)){
                end[k]->next=ptr[l];
                k++;
                if(l!=9) l++;   
            }

        }//End of linking for loop

        cout << "Print results" <<endl;
        printBucket();

        for(j=0;j<10;j++)
            bucket[i]->next=NULL;                       
        cout << "End of iteration" <<endl;
    }//End of radix sort loop
}

int main(){
    int testcases,i,input;
    cin >> testcases;
    int list[testcases];
    int *ptr=&list[0];
    for(i=0;i<testcases;i++){
        cin>>list[i];
    }

    radixSort(ptr,testcases);
    return 0;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-08-13 12:12:19

我认为你的解决方案过于复杂了。您可以使用在输入中接收到的单个数组实现基数,每个步骤中的存储桶由一个索引数组表示,这些索引用于标记输入数组中每个存储桶的起始索引。

实际上,您甚至可以递归地执行此操作:

代码语言:javascript
复制
// 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);
    }
}

当然,当i为9时,buckets[i+1] - buckets[i]会导致缓冲区溢出,但出于可读性的考虑,我省略了额外的检查;我相信您知道如何处理它。

这样,您只需调用radixSort(testcases, sizeof(testcases) / sizeof(testcases[0]), 0),就可以对数组进行排序。

票数 14
EN

Stack Overflow用户

发布于 2016-11-07 11:18:59

为了通过更好的内存管理来加快处理速度,可以通过对数组进行一次遍历,为转换为索引的计数创建一个矩阵。分配另一个与原始数组大小相同的临时数组,并在两个数组之间进行基数排序,直到该数组排序完毕。如果执行奇数次基数排序,则需要将临时数组复制回末尾的原始数组。

要进一步加快该过程,请使用基数256而不是基数10进行基数排序。这只需要1次扫描就可以创建矩阵,只需要4次基数排序就可以进行排序。示例代码:

代码语言:javascript
复制
typedef unsigned int uint32_t;

uint32_t * RadixSort(uint32_t * a, size_t count)
{
size_t mIndex[4][256] = {0};            // count / index matrix
uint32_t * b = new uint32_t [COUNT];    // allocate temp array
size_t i,j,m,n;
uint32_t u;
    for(i = 0; i < count; i++){         // generate histograms
        u = a[i];
        for(j = 0; j < 4; j++){
            mIndex[j][(size_t)(u & 0xff)]++;
            u >>= 8;
        }       
    }
    for(j = 0; j < 4; j++){             // convert to indices
        m = 0;
        for(i = 0; i < 256; i++){
            n = mIndex[j][i];
            mIndex[j][i] = m;
            m += n;
        }       
    }
    for(j = 0; j < 4; j++){             // radix sort
        for(i = 0; i < count; i++){     //  sort by current lsb
            u = a[i];
            m = (size_t)(u>>(j<<3))&0xff;
            b[mIndex[j][m]++] = u;
        }
        std::swap(a, b);                //  swap ptrs
    }
    delete[] b;
    return(a);
}
票数 2
EN

Stack Overflow用户

发布于 2009-08-13 13:29:59

由于您的值是介于0...1,000,000之间的整数

您可以创建一个大小为1,000,001的整型数组,并在两次遍历中完成整个操作

将第二个数组初始化为全零。

遍历您的输入数组,并使用该值作为下标以递增第二个数组中的值。

一旦你这样做了,那么第二次传递就很容易了。遍历第二个数组,每个元素都会告诉您该数字在原始数组中出现了多少次。使用该信息重新填充您的输入数组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1271367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档