基数排序

xiaoxiao2021-02-28  120

原理类似桶排序,这里总是需要10个桶,多次使用 首先以个位数的值进行装桶,即个位数为1则放入1号桶,为9则放入9号桶,暂时忽视十位数 例如 待排序数组[62,14,59,88,16]简单点五个数字 分配10个桶,桶编号为0-9,以个位数数字为桶编号依次入桶,变成下边这样 |  0  |  0  | 62 |  0  | 14 |  0  | 16 |  0  |  88 | 59 | |  0  |  1  |  2  |  3  |  4 |  5  |  6  |  7  |  8  |  9  |桶编号 将桶里的数字顺序取出来, 输出结果:[62,14,16,88,59] 再次入桶,不过这次以十位数的数字为准,进入相应的桶,变成下边这样: 由于前边做了个位数的排序,所以当十位数相等时,个位数字是由小到大的顺序入桶的,就是说,入完桶还是有序 |  0  | 14,16 |  0  |  0  |  0  | 59 | 62  | 0  | 88  |  0  | |  0  |  1      |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |桶编号 因为没有大过100的数字,没有百位数,所以到这排序完毕,顺序取出即可

最后输出结果:[14,16,59,62,88]

public void radixSort(int[] nums){ //首先确定要排序的趟数 int max=nums[0]; for(int i=1;i<nums.length;i++){ if(nums[i]>max) max=nums[i]; } int time=0; while(max>0){ max/=10; time++; } //建10个桶 List<Queue<Integer>> bucket=new ArrayList<Queue<Integer>>(); for(int i=0;i<10;i++){ Queue<Integer> queue=new LinkedList<Integer>(); bucket.add(queue); } for(int i=0;i<time;i++){ for(int j=0;j<nums.length;j++){ int x=(int) ((nums[j]/Math.pow(10, i))); Queue<Integer> values=bucket.get(x); values.add(nums[j]); bucket.set(x, values); } //将桶里的数字顺序输出 int count=0; for(int k=0;k<10;k++){ while(!bucket.get(k).isEmpty()){ nums[count++]=bucket.get(k).poll(); } } } }

转载请注明原文地址: https://www.6miu.com/read-34820.html

最新回复(0)