基数排序

public static void main(String[] args) {

    int arr[] ={12,1,123,117,60,100,90};
    RadixSort(arr);
    System.out.println(Arrays.toString(arr));
}

public static int [] RadixSort(int arr[]) {

    //获取最大数的位数
    Integer max = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    int maxLength = String.valueOf(max).length();
    //获取个位数十位数 ...
    for (int i = 0, n = 1; i < maxLength; i++, n = n * 10) {
        int[][] bucket = new int[10][arr.length];
        int[] count = new int[10];
        for (int j = 0; j < arr.length; j++) {
            int num = arr[j] / n % 10;
            bucket[num][count[num]] = arr[j] ;
            count[num]++;
        }
        int index = 0;
        for (int k = 0; k < bucket.length; k++) {
            if (count[k] > 0) {
                for (int c = 0; c < count[k]; c++) {
                    arr[index] = bucket[k][c];
                    index++;
                }
            }
        }
    }
    return arr;
}

你可能感兴趣的:(基数排序)