import java.util.Arrays; public class My { public void radixSort(int[] arr) { int max = arr[0]; //初始化最大值 for (int a : arr) { if (a > max) { max = a; } } int count = 1; //初始化最大值的位数 while (max / 10 > 0) { //int r=max%10; //余数 max = max / 10; count++; } for (int i = 0; i < count; i++) { int div = 1; //用来取整的被除数 for (int j = i; j > 0; j--) { div *= 10; } int[] temp = new int[arr.length]; int[] buckets = new int[10]; for (int a : arr) { int p = a / div % 10; buckets[p]++; } for (int j = 1; j < 10; j++) { buckets[j] += buckets[j - 1]; } for (int j = arr.length - 1; j >= 0; j--) { int p = arr[j] / div % 10; temp[buckets[p] - 1] = arr[j]; buckets[p]--; } //System.arraycopy(temp, 0, arr, 0, arr.length); for (int j = 0; j < arr.length; j++) { arr[j] = temp[j]; } } } public static void main(String[] args) { My my = new My(); int[] arr = {5, 6, 1, 2, 4, 7, 2, 3, 4, 6, 4}; my.radixSort(arr); System.out.println(Arrays.toString(arr)); } }
原文:https://www.cnblogs.com/zzyf/p/13423715.html