基数排序(java实现)

基本思想:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。

public class RadixSort {
	public int[] radixSort(int[] data) {
		int max = data[0];
		for (int i = 1; i < data.length; i++) {
			if (data[i] > max) {
				max = data[i];
			}
		}
		int time = 0;
		while (max > 0) {
			max /= 10;
			time++;
		}
		// 设定10个list保存数据
		List<ArrayList<Integer>> queue = new ArrayList<ArrayList<Integer>>();
		for (int j = 0; j < 10; j++) {
			ArrayList<Integer> dataQueue = new ArrayList<Integer>();
			queue.add(dataQueue);
		}

		// 开始进行排序
		for (int i = 0; i < time; i++) {
			for (int j = 0; j < data.length; j++) {
				// 取到当前这个数的对应位置上的一位数
				int x = data[j] % (int) Math.pow(10, i + 1)
						/ (int) Math.pow(10, i);
				ArrayList<Integer> returnQueue = queue.get(x);
				returnQueue.add(data[j]);
				queue.set(x, returnQueue);
			}

			int count = 0;
			for (int k = 0; k < 10; k++) {
				while (queue.get(k).size() > 0) {
					ArrayList<Integer> tempQueue = queue.get(k);
					data[count] = tempQueue.get(0);
					tempQueue.remove(0);
					count++;
				}
			}
		}
		return data;
	}

	public static void main(String args[]) {
		int a[] = { 10,9,8,7,6,5,4,3,2,1};
		int[] result = new RadixSort().radixSort(a);
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值