桶排序与基数排序与计数基数排序

输入只有大小小于M的正整数,可以采用桶式排序。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
//基数排序
void radixSort(vector<string> & arr,int stringLen)
{
    const int BUCKETS=256;
    vector<vector<string>> buckets(BUCKETS);

    //从低有效位开始对每一位分别进行桶排序
    for(int pos=stringLen-1;pos>=0;--pos)
    {
        for(string & s:arr)
        {
            buckets[s[pos]].push_back(std::move(s));
        }

        int idx=0;
        for(auto & theBucket:buckets)
        {
            for(string & s:theBucket)
            {
                arr[idx++]=std::move(s);
            }
            theBucket.clear();
        }

    }
}
//计数基数排序
void countingRadixSort(vector<string> & arr,int stringLen)
{
    const int BUCKETS=256;


    int N=arr.size();
    vector<string> buffer(N);

    vector<string> *in=&arr;
    vector<string> *out=&buffer;

    for(int pos=stringLen-1;pos>=0;--pos)
    {
        vector<int> count(BUCKETS+1);
        //k的项数存在k+1里
        for(int i=0;i<N;++i)
            ++count[(*in)[i][pos]+1];

        //k里存放着小于k的项数
        for(int b=1;b<=BUCKETS;++b)
            count[b]+=count[b-1];

        //将k放在小于自己项数的值的下标处,写完后加1是为了处理重复的情况。
        for(int i=0;i<N;++i)
            (*out)[count[(*in)[i][pos]]++]=std::move((*in)[i]);

        std::swap(in, out);


    }
    //最终结果始终存放在in指向的数组里,当为奇数时,in指向buffer,所以要将其移到arr
    if(stringLen%2==1)
        for(int i=0;i<arr.size();++i)
            (*out)[i]=std::move((*in)[i]);

}


int main()
{
    vector<string> arr={"abcde","12345","ABCDE","abdce"};
    radixSort(arr, 5);
    for(auto & s:arr)
    {
        cout<<s<<endl;
    }
    cout<<"...."<<endl;
    countingRadixSort(arr, 5);
    for(auto & s:arr)
    {
        cout<<s<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值