基数排序

package demo;

public class P51 {
//基数排序
//思路:数组中最大值位数为k,从个位开始往高位进行k轮(桶排序+填回原数组),每轮以那一位的数字为分桶的依据
	public static void main(String[] args) {
        int[] a = {49, 38, 65, 197, 76, 213, 27, 50};
        radixSort(a, getMaxPos(a));
        for (int i : a)
            System.out.print(i + ", ");
	}
	
    //pos=1表示个位,pos=2表示十位
    public static int getNumInPos(int num, int pos) {
        int tmp = 1;
        for (int i = 0; i < pos - 1; i++) {
            tmp *= 10;
        }
        return (num / tmp) % 10;
    }
 
    //求得最大位数d
    public static int getMaxPos(int[] a) {
        int max = a[0];
        for (int i = 0; i < a.length; i++) {
            if (a[i] > max)
                max = a[i];
        }
        int d=1;
        while(max/10 != 0) {
        	d++;
        	max=max/10;
        }
        	
        return d;
    }
 
    public static void radixSort(int[] a, int maxPos) {
 
        int[][] array = new int[10][a.length + 1];
        for (int i = 0; i < 10; i++) {
            array[i][0] = 0;// array[i][0]记录第i行数据的个数
        }
        
        for (int pos = 1; pos <= maxPos; pos++) {
        	// 分配的过程
            for (int i = 0; i < a.length; i++) {		
                int row = getNumInPos(a[i], pos);
                int col = ++array[row][0];
                array[row][col] = a[i];
            }
            // 收集的过程
            for (int row = 0, i = 0; row < 10; row++) {
                for (int col = 1; col <= array[row][0]; col++) {
                    a[i++] = array[row][col];
                }
                array[row][0] = 0;		//清0,下一轮pos时还需使用
            }
        }
    }
	
}
posted @   fighterk  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示