基数排序

基数排序是有两种选择,一种是高位优先法(MSD)(Most Significant Digit first),一种是低位优先法(LSD)(Least Significant Digit first),后者是先按个位数大小进行排序,再依次向高位排序。

 

 1 //基数排序
 2 public class RadixSort 
 3 {
 4     public void radixSort(int[] r,int radix,int distance)
 5     {
 6         /*
 7         temp是缓存数组
 8         buckets是待排序元素按关键字的计数
 9         distance是待排序元素的最高位数
10         */
11         int length=r.length;
12         int[] temp=new int[length];
13         int[] buckets=new int[radix];
14         int rate=1;
15         for(int i=0;i<distance;i++)
16         {
17             for(int k=0;k<length;k++)
18             {
19                 temp[k]=r[k];
20             }
21             //下面是计数排序
22             for(int k=0;k<radix;k++)
23             {
24                 buckets[k]=0;
25             }
26             for(int j=0;j<length;j++)
27             {
28                 //计算按比较位数关键字的个数
29                 buckets[(temp[j]/rate)%radix]++;
30             }
31             for(int j=1;j<radix;j++)
32             {
33                 buckets[j]=buckets[j]+buckets[j-1];
34             }
35             for(int j=length-1;j>=0;j--)
36             {
37                 //从后面开始扫描,在计数数组中-1后按计数中的数插入到r数组中
38                 r[--buckets[(temp[j]/rate)%radix]]=temp[j];
39             }
40             rate*=radix;
41         }
42     }
43     public static void main(String[] args) 
44     {
45         RadixSort c=new RadixSort();
46         int[] a={4,345,878565,58,33,234334,34526,89779,71312,25,2,171312};
47         c.radixSort(a,10,6);
48         for(int i=0;i<a.length;i++) 
49             System.out.print(a[i]+" ");
50     }
51 }

 

 

 

posted @ 2013-10-27 21:38  JMSXH  阅读(386)  评论(0编辑  收藏  举报