基数排序

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

void Show(vector<int> & vec)
{
    vector<int> :: iterator   it = vec.begin();
    for(it;it != vec.end();it++)
    {
        cout<<*it<<"  ";
    }
    cout<<endl;
}


//统计出最大宽度
int  Count(vector<int> & vec)
{
    int len = vec.size();
    int max = vec[0];

    for(int i = 0;i < len;++i)
    {
        if(max < vec[i])
        {
            max = vec[i];
        }
    }
    int count = 0;
    while(max)
    {
        max /= 10;
        count++;
    }
    return count;
}

int  Num(int val,int figure)
{
    int tmp = 0;
    for(int i = 0;i <= figure;++i)
    {
        tmp = val%10;
        val /= 10;
    }
    return tmp;
}


//从右往左数第figure个元素
void Radix(vector<int> & vec,int len,int figure)
{
    queue<int>  que[10];
    int tmp = 0;
    vector<int> :: iterator  it = vec.begin();
    for(;it < vec.end();++it)
    {
        tmp = Num(*it,figure);
        que[tmp].push(*it);
    }

    int j = 0;
    for(int i = 0;i < 10;++i)
    {
        while(!que[i].empty())
        {
            vec[j++] = que[i].front();
            que[i].pop();
        }
    }
}


void RadixSort(vector<int> & vec)//时间复杂度N*M,空间复杂度N,稳定
{
    int len = vec.size();
    if(len < 2)return ;

    int figure = Count(vec);
    for(int i = 0;i < figure;++i)
    {
        Radix(vec,len,i);
    }
}


int main()
{
    int arr[10] = {10,9,8,72,6,4,5,2,1,3};
    vector<int>  vec(arr,arr+10);
    Show(vec);
    RadixSort(vec);
    Show(vec);
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页