基数排序又是一种和前面排序方式不一样的排序方式,基数排序不须要进行记录关键字之间的比较。基数排序是一种借助多关键字排序思想对单逻辑关键字进行排序的方法。所谓的多关键字排序就是有多个优先级不一样的关键字。好比说成绩的排序,若是两我的总分相同,则语文高的排在前面,语文成绩也相同则数学高的排在前面。。。若是对数字进行排序,那么个位、十位、百位就是不一样优先级的关键字,若是要进行升序排序,那么个位、十位、百位优先级一次增长。基数排序是经过屡次的收分配和收集来实现的,关键字优先级低的先进行分配和收集。 数组
举个栗子: code
实现代码:
orm
public class RadixSort { public static void radixSort(int[] arr) { if(arr == null & arr.length == 0) return ; int maxBit = getMaxBit(arr); for(int i=1; i) { List> buf = distribute(arr, i); //分配 collecte(arr, buf); //收集 } } /** * 分配 * @param arr 待分配数组 * @param iBit 要分配第几位 * @return */ public static List> distribute(int[] arr, int iBit) { List> buf = new ArrayList>(); for(int j=0; j) { buf.add(new LinkedList()); } for(int i=0; i) { buf.get(getNBit(arr[i], iBit)).add(arr[i]); } return buf; } /** * 收集 * @param arr 把分配的数据收集到arr中 * @param buf */ public static void collecte(int[] arr, List> buf) { int k = 0; for(List bucket : buf) { for(int ele : bucket) { arr[k++] = ele; } } } /** * 获取最大位数 * @param x * @return */ public static int getMaxBit(int[] arr) { int max = Integer.MIN_VALUE; for(int ele : arr) { int len = (ele+"").length(); if(len > max) max = len; } return max; } /** * 获取x的第n位,若是没有则为0. * @param x * @param n * @return */ public static int getNBit(int x, int n) { String sx = x + ""; if(sx.length() n) return 0; else return sx.charAt(sx.length()-n) - '0'; } }