java排序實現之基數排序

package com.attongji.sort.myself;

import java.util.Arrays;

public class RadixSort {
	public static void main(String[] args) {
		int[] arr = new int[10];
		for (int i = 0; i < 10; i++) {
			arr[i] = (int) (Math.random() * 100); // 生成一個[0, 10) 數
		}
		System.out.println("排序前");
		System.out.println(Arrays.toString(arr));

		radixsort(arr);

		System.out.println("排序後");
		System.out.println(Arrays.toString(arr));
	}

	public static void radixsort(int[] arr) {
		int max = arr[0];
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > max)
				max = arr[i];
		}

		int maxLength = (max + "").length();
		System.out.println("maxLength:" + maxLength);

		int[][] bucket = new int[10][arr.length];
		int[] digitCountElement = new int[10];

		for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
			for (int j = 0; j < arr.length; j++) {
				int digitelement = arr[j] / n % 10;
				System.out.println(digitelement);
				bucket[digitelement][digitCountElement[digitelement]] = arr[j];
				digitCountElement[digitelement]++;
			}
			int index = 0;
			for (int k = 0; k < digitCountElement.length; k++) {
				if (digitCountElement[k] != 0) {
					for (int l = 0; l < digitCountElement[k]; l++) {
						arr[index++] = bucket[k][l];
					}
				}
				digitCountElement[k] = 0;
			}
			

		}

	}
}