前幾天師兄問我基數排序怎麼實現,原理我很清楚啊,就給他說了,但是當他詳細問道用具體的計數排序怎樣實現時,我盡然沒有詳細的實現思路。今天有空就把它實現了。不懂理論不行,但是光知道一點理論知識,不去動手實踐是不行的,以後還是要多思,多做。
詳細代碼如下:
package com.algorithm.sort;import java.util.Arrays;public class RadixSort {//基於計數排序的基數排序演算法private static void radixSort(int[] array,int radix, int distance) {//array為待排序數組//radix,代表基數//代表排序元素的位元int length = array.length;int[] temp = new int[length];//用於暫存元素int[] count = new int[radix];//用於計數排序int divide = 1;for (int i = 0; i < distance; i++) {System.arraycopy(array, 0,temp, 0, length);Arrays.fill(count, 0);for (int j = 0; j < length; j++) {int tempKey = (temp[j]/divide)%radix;count[tempKey]++;}for (int j = 1; j < radix; j++) {count [j] = count[j] + count[j-1];}//個人覺的運用計數排序實現計數排序的重點在下面這個方法for (int j = length - 1; j >= 0; j--) {int tempKey = (temp[j]/divide)%radix;count[tempKey]--;array[count[tempKey]] = temp[j];}divide = divide * radix;}}/** * @param args */public static void main(String[] args) {int[] array = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};radixSort(array,10,7);for (int i = 0; i < array.length; i++) {System.out.print(" " + array[i]);}}}