publicstaticvoidradixSort(int arr[]){ //获取最大位数 int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } //计算位数 int maxLength = (max + "").length();
for (int i = 0, n = 1; i < maxLength; i++, n *= 10) { for (int j = 0; j < arr.length; j++) { int digitOfElemt = arr[j] / n % 10; bucket[digitOfElemt][bucketElemtCounts[digitOfElemt]] = arr[j]; bucketElemtCounts[digitOfElemt]++; } int index = 0; for (int k = 0; k < bucketElemtCounts.length; k++) { if (bucketElemtCounts[k] != 0) { for (int l = 0; l < bucketElemtCounts[k]; l++) { arr[index++] = bucket[k][l]; } } bucketElemtCounts[k] = 0; } System.out.println("第"+(i+1)+"轮排序"); System.out.println(Arrays.toString(arr)); }
publicclassRadixSort{ publicstaticvoidmain(String[] args){ int max = 80000; int[] arr = newint[max]; for (int i = 0; i < max; i++) { arr[i] = (int)(Math.random() * 80000); } long date1 = System.currentTimeMillis(); radixSort(arr); long date2 = System.currentTimeMillis(); System.out.println("位移式希尔排序"+max+"数组的时间为:"+(date2-date1)); }
publicstaticvoidradixSort(int arr[]){ //获取最大位数 int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } //计算位数 int maxLength = (max + "").length();
for (int i = 0, n = 1; i < maxLength; i++, n *= 10) { for (int j = 0; j < arr.length; j++) { int digitOfElemt = arr[j] / n % 10; bucket[digitOfElemt][bucketElemtCounts[digitOfElemt]] = arr[j]; bucketElemtCounts[digitOfElemt]++; } int index = 0; for (int k = 0; k < bucketElemtCounts.length; k++) { if (bucketElemtCounts[k] != 0) { for (int l = 0; l < bucketElemtCounts[k]; l++) { arr[index++] = bucket[k][l]; } } bucketElemtCounts[k] = 0; } } } }