基数排序简单实现

public class RadixSort {
    public static void main(String[] args) {
        int[] arr={23,435,1,45,666,85,30,77};
        System.out.println("排序前:"+Arrays.toString(arr));
        int max=arr[0];
        for (int i = 0; i max){
                max=arr[i];
            }
        }
        int maxLen=(max+"").length();
        int[][] bucket=new int[10][arr.length];
        int[] bucketElementCounts=new int[10];
        for (int i = 0,n=1; i < maxLen; i++,n*=10) {
            for (int j = 0; j < arr.length; j++) {
                int digit=arr[j]/n%10;
                bucket[digit][bucketElementCounts[digit]++]=arr[j];
            }
            int index=0;
            for (int k = 0; k < bucket.length; k++) {
                if (bucketElementCounts[k]!=0){
                    for (int l = 0; l < bucketElementCounts[k]; l++) {
                        arr[index++]=bucket[k][l];
                    }
                    bucketElementCounts[k]=0;
                }
            }
            System.out.println(Arrays.toString(arr));
            System.out.println("===========");
        }
        System.out.println("排序后:"+ Arrays.toString(arr));
    }
}

你可能感兴趣的:(java,排序)