基数排序

引用http://yoyo08.iteye.com/blog/464556
public class RadixSortTrain   
{   
            int [] a ={785,121,2131,123,4567,452,12,34,78,1234};   
            public void printA()   
            {   
                for(int i=0;i<a.length;i++)   
                    System.out.println(a[i]);   
                }   
                   
            public void RadixSort(int length)   
            {   
                for(int i =1;i <=length;i++) //length应该为数组最大值的位数;   
                            Radix(i);   
                   
                }      
               
            public void Radix(int length)   
            {   
                int [] count = new int[10];  //用于计数   
                int [] temp = new int[a.length];  //用于临时存放数据   
                   
                int s = 1;   
                for(int i = 0; i <=length;i++)   
                            s = s * 10;//算出当前的基数 从10开始 100 1000....   
               
                int temp1 = 0;   
                for(int j = 0 ; j < a.length; j++)   
                {   
                    temp1 = a[j]%s;   
                    temp1 = temp1 * 10 / s;   
                    count[temp1]++;     
                    }   
                   
                for(int k=1;k < a.length;k++) //调整计数;   
                    count[k] = count[k] + count[k-1];   
                    int temp2 = 0;   
                for(int m = a.length-1; m >= 0 ; m--)   
                    {   
                        temp1 = a[m];   
                        temp2 = a[m]%s;   
                        temp2 = temp2*10/s;   
                        temp[count[temp2]-1] = temp1;   
                        count[temp2]--;//一轮结束 temp中存放的是第i位的有序数组   
                           
                        }   
                    for(int n = 0;n < a.length ;n++)   
                        a[n] = temp[n];   //将temp赋值给a   
                   
                }   
            public static void main(String args[])   
        {   
            RadixSortTrain rst = new RadixSortTrain();   
            rst.RadixSort(4);   
            rst.printA();   
            }   
} 

你可能感兴趣的:(Blog)