/**
* 打印數(shù)組內(nèi)容
*
* @param a
*/
public static void saymsg(int[] src) {
for (int i = 0; i < src.length; i++) {
System.out.print(src[i]);
System.out.print(",");
}
System.out.println();
}
public static void sort(int[] array) { // 首先確定排序的趟數(shù); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } }
int time = 0; // 判斷位數(shù); 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++) { // 分配數(shù)組元素; for (int j = 0; j < array.length; j++) { // 得到數(shù)字的第time+1位數(shù); 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;// 元素計數(shù)器; // 收集隊列元素; for (int k = 0; k < 10; k++) { ArrayList<Integer> queue3 = queue.get(k); while (queue3.size() > 0) { array[count] = queue3.get(0); queue3.remove(0); count++; } } saymsg(array); } }
public static void main(String[] args) { int[] src = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; System.out.println("原始數(shù)組排序:"); saymsg(src); if (src.length > 0) { sort(src); } }
Data Structure Visualizations 提供了一個基數(shù)排序的分步動畫演示http://www.cs.usfca.edu/~galles/visualization/RadixSort.html
更多建議: