1、基数排序介绍
基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或bin sort,顾名思义,它是透过键值的部份资讯,将要排序的元素分配至某些“桶”中,藉以达到排序的作用,基数排序法是属于稳定性的排序,其时间复杂度为O
(nlog(r)m),其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。
2、基数排序的方式
分为MSD和LSD两种方式,LSD为从个位、十位、百位,从后往前以关键字进行排序,MSD恰好相反。它从高位向低位进行。
LSD的示例可以见百度百科http://baike.baidu.com/link?url=8kJVFNtp41O2KY4v93wTzob10hnuN6v4X0lDAOIQJIJwt084FouOrd5N7hL-_1nzrjD18U8LGYwqFgt_KJtZGK
3、基数排序实现
以Java语言实现LSD方式的基数排序
public class RadixSort {
private int[] pArrayofInts;
private int n;
public RadixSort(int[] pArrayofInts, int n) {
this.pArrayofInts = pArrayofInts;
this.n = n;
}
public void printArray() {
for (int i = 0; i < pArrayofInts.length; i++) {
System.out.print(pArrayofInts[i] + "、");
}
System.out.println();
}
public void doSort() {
int d = 1;
int[][] pBucket = new int[10][pArrayofInts.length];
while (d < n) {
for (int pIndex = 0; pIndex < pArrayofInts.length * 10; pIndex++) {
pBucket[pIndex / pArrayofInts.length][pIndex
% pArrayofInts.length] = -1;
}
for (int pIndex = 0; pIndex < pArrayofInts.length; pIndex++) {
int pKey = pArrayofInts[pIndex] / d % 10;
pBucket[pKey][pIndex] = pArrayofInts[pIndex];
}
for (int pIndex = 0, pArrayIndex = 0; pIndex < pArrayofInts.length * 10; pIndex++) {
if ((pBucket[pIndex / pArrayofInts.length][pIndex
% pArrayofInts.length] != -1)) {
pArrayofInts[pArrayIndex++] = pBucket[pIndex
/ pArrayofInts.length][pIndex % pArrayofInts.length];
}
}
d = d * 10;
}
}
}
如下为Main函数
public class Main {
public static void main(String[] args) {
int[] pArrayofInts = { 3, 5, 6, 22, 1, 0, 4 ,87,902,111};
RadixSort pRadixSort = new RadixSort(pArrayofInts,1000);
System.out.println("排序前:");
pRadixSort.printArray();
pRadixSort.doSort();
System.out.println("排序后:");
pRadixSort.printArray();
}
}
输出结果如下:
排序前:
3、5、6、22、1、0、4、87、902、111、
排序后:
0、1、3、4、5、6、22、87、111、902、
3、5、6、22、1、0、4、87、902、111、
排序后:
0、1、3、4、5、6、22、87、111、902、