RadixSort

Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. A positional notation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not limited to integers. Radix sort dates back as far as 1887 to the work ofHerman Hollerith on tabulating machines.

 

 1 /*
 2  * Average    Worst     Memory   Stable
 3  *  n*k        n*k       n+r        No
 4 */
 5 public class RadixSort {
 6     
 7     private static final int BITS_PER_GROUPS = 4;
 8     private static final int GROUPS_COUNT=32/BITS_PER_GROUPS;
 9     
10     private static final int[] MASK_TABLE=new int[GROUPS_COUNT];
11     static{
12         MASK_TABLE[0]=(1<<BITS_PER_GROUPS)-1;
13         for(int i=1;i<MASK_TABLE.length;i++){
14             MASK_TABLE[i]=MASK_TABLE[i-1]<<BITS_PER_GROUPS;
15         }
16     };
17 
18     public static void radixSort(int[] a){
19         for(int i=0;i<GROUPS_COUNT;i++){
20             int mask=MASK_TABLE[i];
21             int[] counting=new int[1<<BITS_PER_GROUPS];
22             for(int j=0;j<a.length;j++){
23                 counting[(a[j]&mask)>>>(i*BITS_PER_GROUPS)]++;
24             }
25             for(int j=1;j<counting.length;j++){
26                 counting[j]+=counting[j-1];
27             }
28             int[] temp=new int[a.length];
29             for(int j=a.length -1;j>=0;j--){
30                 temp[--counting[(a[j]& mask)>>>(i*BITS_PER_GROUPS)]]=a[j];
31             }
32             System.arraycopy(temp, 0, a, 0, temp.length);
33         }
34         
35     }
36     
37     public static void printArray(int[] a){
38         for(int i = 0;i < a.length;i++){
39             System.out.print(a[i]+" ");
40         }
41     }
42     
43     public static void main(String[] args) {
44         int[] input = new int[] {16, 14, 10, 8, 7, 9, 3, 2, 4, 1}; 
45         radixSort(input);
46         printArray(input);
47     }
48 
49 }

 

posted on 2013-03-31 10:41  melotang  阅读(266)  评论(0)    收藏  举报