排序算法-基数排序

    基数排序是一种非比较排序算法,它将待排序的数字按照位数进行排序。基数排序的思想是先按照个位数进行排序,然后按照十位数进行排序,接着按照百位数进行排序,以此类推,直到最高位排序完成。

    基数排序的步骤如下:

 

代码思路:

class RadixSort{
	public static void redixSort(int[] arr){
		if (arr==null || arr.length <2){
			return;
		}
		redixSort(arr,0,arr.length-1,maxbits(arr));
	}


	//求最大数有多少位
	private static int maxbits(int[] arr) {
		int max = Integer.MIN_VALUE;
		for(int a: arr){
			max=Math.max(max,a);
		}
		int res=0;
		while (max != 0){
			res++;
			max/=10;
		}
		return res;
	}

	private static void redixSort(int[] arr, int l, int r, int digit) {
		final int radix=10;
		int i=0,j=0;
		//定义一个与arr长度相等的数组
		int[] help =new int[r-l+1];
		//有多少位就循环几次,从个位开始
		for (int d=1;d<=digit;d++){
			//count和count‘都用count表示
			//count[0] 当前位(d位)是0的数字有多少个
			//count[1] 当前位(d位)是(0和1)的数字有多少个
			//count[2] 当前位(d位)是(0和1和2)的数字有多少个
			//count[i] 当前位(d位)是(0~i)的数字有多少个
			int[] count=new int[radix];//count[0..9]
			//count
			for (i=l;i<=r;i++){
				j=getDigit(arr[i],d);
				count[j]++;
			}
			//count’
			for (i=1;i<radix;i++){
				count[i]=count[i]+count[i-1];
			}
			//从右往左遍历,对应的数放到help中
			for (i=r;i>=l;i--){
				j=getDigit(arr[i],d);
				help[count[j]-1] = arr[i];
				count[j]--;
			}
			//help数组赋值给结果数组
			for (i=l, j=0;i<=r;i++,j++){
				arr[i] =help[j];
			}
		}

	}

	//取出当前数对应位数的数,如x=109,d=1,相当于取109个位上的数,即9
	private static int getDigit(int x,int d){
		return ((x/((int) Math.pow(10,d-1))) % 10);
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@好好学习天天向上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值