基础算法系列 之基数排序

基数排序是一种独立的排序思想,其排序准则就是“按位分组,再行排序”,适用于不同位数的排序。其代码如下:

public static void radixSort(int[]arr){
    
    
	int [][] temp = new int[10][arr.length];
	int max = Integer.MIN_VALUE;	//存最大数
	int [] counts = new int[10];
	for(int i=0;i<arr.length;i++){
    
    
		if(arr[i] > max){
    
    
			max = arr[i];
		}
	}
	int maxLength = (max+"").length;	//求最大数位数
	for(int i=0,n=1;i<maxLength;i++,n*=10){
    
    	//决定循环次数
		for(int j=0;j<arr.length;j++){
    
    
			int ys = arr[j]/n%10;
			temp[ys][counts[ys]] = arr[j];
			counts[ys]++;
		}
		if(i==0){
    
    
			for(int[]nums:temp){
    
    
				System.out.println(Arrays.toString(nums));
			}
		}
		for(int k=0;k<counts.length;k++){
    
    
			if(counts[k]!=0){
    
    
				for(int l=0;l<counts[k];l++){
    
    
					arr[index]++ = temp[k][l];
				}
				counts[k] = 0;
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/langxiaolin/article/details/113075222
今日推荐