基数排序的正确性证明可以用数学归纳法,《算法导论》第三版习题8.3-3。里面需要一个概念:排序算法的稳定性。
package class03P;
import java.util.Arrays;
public class Code01P_CountSort {
public static void countSort(int[] arr){
if(arr == null ||arr.length < 2) return;
int[] help = new int[200];
for (int i = 0; i < arr.length; i++) {
help[arr[i]]++;
}
int index = 0;
for (int i = 0; i < help.length; i++) {
while(help[i]-- > 0){
arr[index++] = i;
}
}
}
public static void main(String[] args) {
int[] arr = {92, 97, 150, 50, 64, 12, 38, 60, 12};
System.out.println(Arrays.toString(arr));
countSort(arr);
System.out.println(Arrays.toString(arr));
}
}
package class03P;
import java.util.Arrays;
public class Code02P_RadixSort {
public static void RadixSort(int[] arr){
if(arr == null || arr.length < 2) return;
int d = maxBits(arr);
int[] bucket = new int[10];
int[] help = new int[arr.length];
for (int i = 1; i <= d; i++) {
for (int j = 0; j < bucket.length; j++) {
bucket[j] = 0;
}
for (int j = 0; j < arr.length; j++) {
bucket[getDigit(arr[j], i)]++;
}
for (int j = 1; j < bucket.length; j++) {
bucket[j] += bucket[j - 1];
}
for (int j = arr.length - 1; j >= 0; j--) {
help[--bucket[getDigit(arr[j], i)]] = arr[j];
}
System.arraycopy(help, 0, arr, 0,help.length);
}
}
public static int maxBits(int[] arr){
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(arr[i], max);
}
int res = 0;
for(; max > 0; max /= 10){
res++;
}
return res;
}
public static int getDigit(int a, int d){
return ((a / ((int)Math.pow(10, d - 1))) % 10);
}
public static void main(String[] args) {
int[] arr = {23, 345, 1, 0};
RadixSort(arr);
System.out.println(Arrays.toString(arr));
}
}
|