package wzs.sort;// 基數排序// 將所有待比較數值(正整數)統一為同樣的數位長度,數位較短的數前面補零。然後,從最低位開始,依次進行一次排序。// 這樣從最低位排序一直到最高位排序完成以後,數列就變成一個有序序列。import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class radixSort{ public static void main(String[] args) { int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 101, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; sort(a); System.out.println("排序後:" + Arrays.toString(a)); } public static void sort(int[] array) { // 首先確定排序的趟數; int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } int time = 0; // 判斷位元; while (max > 0) { max /= 10; time++; } // 建立10個隊列; List<ArrayList> queue = new ArrayList<ArrayList>(); for (int i = 0; i < 10; i++) { ArrayList<Integer> queue1 = new ArrayList<Integer>(); queue.add(queue1); } // 進行time次分配和收集; for (int i = 0; i < time; i++) { // 分配數組元素; for (int j = 0; j < array.length; j++) { // 得到數位第time+1位元; int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i); ArrayList<Integer> queue2 = queue.get(x); queue2.add(array[j]); queue.set(x, queue2); } int count = 0;// 元素計數器; // 收集隊列元素; for (int k = 0; k < 10; k++) { while (queue.get(k).size() > 0) { ArrayList<Integer> queue3 = queue.get(k); array[count] = queue3.get(0); queue3.remove(0); count++; } } } }}