|
| 1 | +package org.algorithm.array.sort.impl; |
| 2 | + |
| 3 | +import org.algorithm.array.sort.interf.Sortable; |
| 4 | + |
| 5 | +/** |
| 6 | + * <p> |
| 7 | + * 基数排序/桶排序 |
| 8 | + * </p> |
| 9 | + * 2016年1月19日 |
| 10 | + * |
| 11 | + * @author <a href="http://weibo.com/u/5131020927">Q-WHai</a> |
| 12 | + * @see <a href="http://blog.csdn.net/lemon_tree12138">http://blog.csdn.net/lemon_tree12138</a> |
| 13 | + * @version 0.1.1 |
| 14 | + */ |
| 15 | +public class RadixSort implements Sortable { |
| 16 | + |
| 17 | + @Override |
| 18 | + public int[] sort(int[] array) { |
| 19 | + if (array == null) { |
| 20 | + return null; |
| 21 | + } |
| 22 | + |
| 23 | + int maxLength = maxLength(array); |
| 24 | + |
| 25 | + return sortCore(array, 0, maxLength); |
| 26 | + } |
| 27 | + |
| 28 | + private int[] sortCore(int[] array, int digit, int maxLength) { |
| 29 | + if (digit >= maxLength) { |
| 30 | + return array; |
| 31 | + } |
| 32 | + |
| 33 | + final int radix = 10; // 基数 |
| 34 | + int arrayLength = array.length; |
| 35 | + int[] count = new int[radix]; |
| 36 | + int[] bucket = new int[arrayLength]; |
| 37 | + |
| 38 | + // 统计将数组中的数字分配到桶中后,各个桶中的数字个数 |
| 39 | + for (int i = 0; i < arrayLength; i++) { |
| 40 | + count[getDigit(array[i], digit)]++; |
| 41 | + } |
| 42 | + |
| 43 | + // 将各个桶中的数字个数,转化成各个桶中最后一个数字的下标索引 |
| 44 | + for (int i = 1; i < radix; i++) { |
| 45 | + count[i] = count[i] + count[i - 1]; |
| 46 | + } |
| 47 | + |
| 48 | + // 将原数组中的数字分配给辅助数组bucket |
| 49 | + for (int i = arrayLength - 1; i >= 0; i--) { |
| 50 | + int number = array[i]; |
| 51 | + int d = getDigit(number, digit); |
| 52 | + |
| 53 | + bucket[count[d] - 1] = number; |
| 54 | + |
| 55 | + count[d]--; |
| 56 | + } |
| 57 | + |
| 58 | + return sortCore(bucket, digit + 1, maxLength); |
| 59 | + } |
| 60 | + |
| 61 | + /* |
| 62 | + * 一个数组中最数字的位数 |
| 63 | + * |
| 64 | + * @param array |
| 65 | + * @return |
| 66 | + */ |
| 67 | + private int maxLength(int[] array) { |
| 68 | + int maxLength = 0; |
| 69 | + int arrayLength = array.length; |
| 70 | + for (int i = 0; i < arrayLength; i++) { |
| 71 | + int currentLength = length(array[i]); |
| 72 | + if (maxLength < currentLength) { |
| 73 | + maxLength = currentLength; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return maxLength; |
| 78 | + } |
| 79 | + |
| 80 | + /* |
| 81 | + * 计算一个数字共有多少位 |
| 82 | + * |
| 83 | + * @param number |
| 84 | + * @return |
| 85 | + */ |
| 86 | + private int length(int number) { |
| 87 | + return String.valueOf(number).length(); |
| 88 | + } |
| 89 | + |
| 90 | + /* |
| 91 | + * 获取x这个数的d位数上的数字 |
| 92 | + * 比如获取123的0位数,结果返回3 |
| 93 | + * |
| 94 | + * @param x |
| 95 | + * @param d |
| 96 | + * @return |
| 97 | + */ |
| 98 | + private int getDigit(int x, int d) { |
| 99 | + int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; |
| 100 | + return ((x / a[d]) % 10); |
| 101 | + } |
| 102 | +} |
0 commit comments