排序算法-基数排序

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

基数排序的步骤如下:

代码思路:

java 复制代码
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);
	}
}
相关推荐
gugugu.6 分钟前
算法:滑动窗口类型题目的总结
算法·哈希算法
大数据张老师32 分钟前
数据结构——直接插入排序
数据结构·算法·排序算法·1024程序员节
hoiii18737 分钟前
基于SVM与HOG特征的交通标志检测与识别
算法·机器学习·支持向量机
何中应42 分钟前
如何使用Spring Context实现消息队列
java·后端·spring
进击的炸酱面1 小时前
第四章 决策树
算法·决策树·机器学习
四念处茫茫1 小时前
Rust:与JSON、TOML等格式的集成
java·rust·json
摸鱼仙人~1 小时前
一文深入学习Java动态代理-JDK动态代理和CGLIB
java·开发语言·学习
爱coding的橙子1 小时前
每日算法刷题Day81:10.29:leetcode 回溯5道题,用时2h
算法·leetcode·职场和发展
微知语1 小时前
Cell 与 RefCell:Rust 内部可变性的双生子解析
java·前端·rust
雨过天晴而后无语1 小时前
Windchill10+html使用Lightbox轻量化wizard的配置
java·前端·html