文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或bin sort,顾名思义,它是通过键值的各个位的值,将要排序的元素分配至某些“桶”中,达到排序的作用
基数排序法是属于稳定性的排序,基数排序法的是效率高的稳定性排序法
基数排序是1887年赫尔曼·何乐礼发明的。它是这样实现的:将整数按位数切割成不同的数字,然后按每个位数分别比较。
将所有待比较数值统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列。
空间换时间,稳定
package cn.guizimo.sort; import java.util.Arrays; public class RadixSort { public static void main(String[] args) { int arr[] = {53,45,6,378,15,234,78}; System.out.println("排序前"); System.out.println(Arrays.toString(arr)); radixSort(arr); System.out.println("排序后"); System.out.println(Arrays.toString(arr)); } public static void radixSort(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(); int[][] bucket = new int[10][arr.length]; int[] bucketElemtCounts = new int[10]; 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)); } } }
package cn.guizimo.sort; import java.util.Arrays; public class RadixSort { public static void main(String[] args) { int max = 80000; int[] arr = new int[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)); } public static void radixSort(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(); int[][] bucket = new int[10][arr.length]; int[] bucketElemtCounts = new int[10]; 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; } } } }
尚硅谷
万能的网络
以及勤劳的自己