1 package queue_radix; 2 3 public class Queue { 4 int[] queue; 5 6 public Queue(){ 7 queue = new int[0]; 8 } 9 10 public boolean isEmpty(){ 11 return queue.length==0; 12 } 13 14 public void add(int num){ 15 if (isEmpty()){ 16 int[] temp=new int[]{num}; 17 queue = temp; 18 }else { 19 int[] temp=new int[queue.length+1]; 20 for (int i=0;i<queue.length;i++){ 21 temp[i]=queue[i]; 22 } 23 temp[queue.length]=num; 24 queue = temp; 25 } 26 } 27 28 public int poll(){ 29 if (isEmpty()){ 30 throw new RuntimeException("空表"); 31 }else { 32 int val = queue[0]; 33 int[] temp=new int[queue.length-1]; 34 for (int i=0;i<queue.length-1;i++){ 35 temp[i]=queue[i+1]; 36 } 37 queue = temp; 38 return val; 39 } 40 } 41 }
1 package queue_radix; 2 3 import java.util.Arrays; 4 5 public class RadixSortQueue { 6 public static void main(String[] args) { 7 int[] arr = new int[]{3,55,965,1214,111,527,684,952,22,336,11}; 8 System.out.println(Arrays.toString(arr)); 9 radixSort(arr); 10 System.out.println(Arrays.toString(arr)); 11 } 12 13 public static void radixSort(int[] arr){ 14 //取到数组中最大的数 15 int max = 0; 16 for (int i=0;i<arr.length;i++){ 17 if (arr[i]>max){ 18 max=arr[i]; 19 } 20 } 21 22 //计算最大数的位数 23 int maxLength = (max+"").length(); 24 System.out.println(maxLength); 25 26 //安排一个二维数组用于存储临时数据 27 Queue[] temp= new Queue[arr.length]; 28 for (int i=0;i<arr.length;i++){ 29 temp[i]=new Queue(); 30 } 31 32 //根据最大数的位数决定比较的轮数 33 for (int i=0,n=1;i<maxLength;i++,n*=10){ 34 //第一轮取个位 35 for (int j=0;j<arr.length;j++){ 36 //计算标记位 37 int yS = arr[j]/n%10; 38 temp[yS].add(arr[j]); 39 } 40 // System.out.println(Arrays.toString(temp[1].queue)); 41 //桶内元素送还数组 42 int d=0; 43 for (int s=0;s<temp.length;s++){ 44 while (!temp[s].isEmpty()){ 45 arr[d++]=temp[s].poll(); 46 } 47 } 48 // System.out.println(Arrays.toString(arr)); 49 } 50 } 51 }
原文:https://www.cnblogs.com/traodm/p/14460122.html