基数排序(8.2)

来源:互联网 发布:物联网人才需求数据 编辑:程序博客网 时间:2024/06/10 11:26

1.理论

基数排序(以整形为例),将整形10进制按每位拆分,然后从低位到高位依次比较各个位。主要分为两个过程:
(1)分配,先从个位开始,根据位值(0-9)分别放到0~9号桶中(比如53,个位为3,则放入3号桶中)
(2)收集,再将放置在0~9号桶中的数据按顺序放到数组中
重复(1)(2)过程,从个位到最高位(比如32位无符号整形最大数4294967296,最高位10位)
以【521 310 72 373 15 546 385 856 187 147】序列为例,具体细节如下图所示:



在数据中最高位为3,进行了三次分配、收集过程后,变成有序数组。

2.基数排序扩展

排序元素有负数参考:http://blog.csdn.net/feixiaoxing/article/details/6876831

3.C代码

/*************************************************************************> File Name: radixSort.c> Author: NULL> Mail: 574889524@qq.com> Created Time: 2014年11月01日 星期六 21时27分45秒 ************************************************************************//*说明:未包含对负数的排序*/#include <stdio.h>#include <stdlib.h>#define ARRSIZE 10void RadixCountingSort(int *ipIndex,int nMax,int *ipArry,int iLenght);/************************************************************/void print(int *A,int length)  {      int i;      for(i=0;i<length;++i)          printf("%d ",A[i]);      printf("\n");  }  /***********************************************************//*基数排序*/int RadixSort(int *ipArry,int iLenght){    int *ipDataRadix = (int*)malloc(sizeof(int)*iLenght);    int i;    int iRadixBase = 1;/*初始化倍数基数为1*/    int iFlag = 0;/*设置完成排序的0*/    /*循环直到完成基数*/    while(!iFlag){                iFlag = 1;        iRadixBase *= 10;        for(i = 0;i < iLenght;++i){            ipDataRadix[i] = ipArry[i] % iRadixBase;/*计算末尾数字*/            ipDataRadix[i]/= iRadixBase/10;            if(ipDataRadix[i] > 0)                iFlag = 0;        }        if(iFlag) /*如果所有的基数都为0,认为排序完成,就是判断到最高位了*/            break;        RadixCountingSort(ipDataRadix,10,ipArry,iLenght);/*执行计数排序算法*/    }    free(ipDataRadix);}/*计数排序算法* ipIndex:相当于一个将要排序的数组,这个数组中的数字在0--9之间* nMax:为10,原因是上面的数组元素中的数字最大为9* ipArry:基数排序的原始数组* iLenght:基数排序的数组的长度*/void RadixCountingSort(int *ipIndex,int nMax,int *ipArry,int iLenght){    int i,*ipCount,*ipSort;    ipCount=(int*)malloc(sizeof(int)*nMax);/*用于统计数组 ipIndex 数组中元素出现的次数*/    for(i = 0;i <nMax;++i)/* 初始化基数的个数,开始全部为0*/        ipCount[i] = 0;    for(i=0;i < iLenght;++i)/*统计元素出现的次数*/        ipCount[ipIndex[i]]++;    for(i=1;i<10;++i)/*确定不大于该位置的个数*/        ipCount[i]+=ipCount[i-1];        ipSort = (int*)malloc(sizeof(int)*iLenght);/*存放临时排序的结果*/        for(i=iLenght-1;i>=0;--i){        ipSort[ipCount[ipIndex[i]]-1] = ipArry[i];/*将元素放到对应的位置*/        ipCount[ipIndex[i]]--;/*将此元素个数减1*/    }        for(i=0;i<iLenght;++i)/*把排序好的数据返回到原始的基数排序数组*/        ipArry[i] = ipSort[i];    free(ipSort);    free(ipCount);}int main(){    int iArry[ARRSIZE] = {123,5264,9513,854,9639,1985,159,3654,8521,8888};    RadixSort(iArry,ARRSIZE);    print(iArry,ARRSIZE);    return 0;}



0 0
原创粉丝点击