排序-JAVA实现【七】基数排序

package org.lion.euler.study.sort;

/**
 * 基数排序
 * 
 * @author lion
 *
 */
public class RadixSort extends AbstractSort {

	@Override
	public void sort(Integer[] array) {
		int max = 0;
		for(int i = 0; i < array.length; i ++){
			int bit = this.getBit(array[i]);
			if(bit > max){
				max = bit;
			}
		}
		this.sort(array, max);
	}

	private void sort(Integer[] array, int max) {
		Integer[][] radixArray = new Integer[10][array.length];
		int[] radixBit = new int[10];
		int radix = 1;
		while(max -- > 0){
			
			for (int i = 0; i < array.length; i++) {
				int bit = (array[i] / radix) % 10;
				
				radixArray[bit][radixBit[bit]] = array[i];
				radixBit[bit] += 1;
			}

			int index = 0;
			for (int i = 0; i < radixBit.length; i++) {
				for (int j = 0; j < radixBit[i]; j++) {
					array[index ++] = radixArray[i][j];
				}
				radixBit[i] = 0;
			}
			
			radix *= 10;
			
		}
	}

	private int getBit(int value) {
		int bit = 0;
		while (value > 0) {
			value /= 10;
			bit += 1;
		}
		return bit;
	}
}