【C++单排之路】 --基数排序

之前提到的线性时间排序——计数排序,针对于排序数范围跨度较小,额外消耗的空间不大,而对于序列

{56165,313,255,1354,78}甚至更大的数来说,消耗的空间过大。

这时就用到了基数排序,基数排序可以看作计数排序的扩展

//基数排序
//计数排序作为一种线性时间排序算法,当排序数的范围过大,消耗空间也随之变大。
//基数排序可以看作计数排序的一种扩展,将较大的数按基数,纵向使用计数排序
// Author's E-mail : [email protected]  Feel free to contact me for comments on my work
#include<iostream>
using namespace std;
//输出数组函数
void printArray(int *a,int len){
    for (int i = 0; i < len;i++){
        cout << a[i] << "  ";
    }
    cout << endl;
}
int* CountSort(int *a, int len,int rad){
    int c[10];
    int *b = new int[len]; //动态申请数组内存
    for (int i = 0; i < 10;i++){
        c[i] = 0;
    }
    int t = 0;
    for (int i = 0; i < len;i++){
        c[(a[i] / rad)%10]++;
        if((a[i] / rad)%10==0){
            t++;
        }
    }
    if(t==len){
        printArray(a, len);
        return NULL;//排序结束
    }
    for (int i = 1; i < 10;i++){
        c[i] += c[i - 1];
    }
    for (int i = len-1; i >=0;i--){ //这里必须要用倒叙,原因在于当前位若相同,则倒叙可以不影响之前较小位排序结果
        int pos = c[(a[i] / rad) % 10] - 1;

        b[c[(a[i] / rad)%10] - 1] = a[i];
        c[(a[i] / rad)%10]--;
    }
    return b;
}
void RadixSort(int *a,int len){
    int rad = 1;
    while(1){
        a = CountSort(a, len, rad);
        if(a==NULL){
            return;
        }else{
            rad = rad * 10;
        }
    }
}
int main(){
    int array[5] = {56165, 313, 255, 1354, 78};
    RadixSort(array, 5);
    system("pause");
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章