文章目录
前言
基数排序不同于计数排序,它是按照数字本身,位一位的比较,同时赋予高位的更加大大优先级。这很类似与我们比较两个数,是不是从高位比到低位。这里有类似的思想,高位大的大,但是不是从高位相比,而是低位开始比,先排一下,然后拍高位。
一、基数排序
- 先求出这个数组的最大值的位数
- 然后求new出一个同等于原数组的数组进行每一次位的遍历
- new出一个大小与进制基数一样的数组用来做桶划分区间,该数组的值,将代表着接下来,这个数的这个位为这个值的放入new数组的下标
- 接着遍历一次数组,将此时位数的count数组++,目的是为了划分区间
- 然后接着将count[i]=count[i]+count[i-1].用递推的思想求出每一位划分的区间
- 然后从尾部遍历到头部,将该值放到新new出的数组count【位数】-1的地方,然后将count【位数】减一(一定不能从头到尾,这里的遍历顺序暗含低位大小顺序,只不过现在要按优先级更高的高位排了,但是如果高位相同,不这样遍历的话会出错)
- 最后将new出来的数组复制到原数组就行
二、实现步骤
1.先求出这个数组的最大值的位数
代码如下(示例):
public static int maxbits(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
int res = 0;
while (max != 0) {
res++;
max /= 10;
}
return res;
}
2.然后求new出一个同等于原数组的数组进行每一次位的遍历
代码如下(示例):
int[] bucket = new int[end - begin + 1];
3.new出一个大小与进制基数一样的数组用来做桶划分区间
代码如下(示例):
int[] count = new int[radix];
4.接着遍历一次数组,将此时位数的count数组++
代码如下(示例):
for (i = begin; i <= end; i++) {
j = getDigit(arr[i], d);
count[j]++;
}
5.然后接着count[i]=count[i]+count[i-1]
代码如下(示例):
for (i = 1; i < radix; i++) {
count[i] = count[i] + count[i - 1];
}
6.然后从尾部遍历到头部
代码如下(示例):
for (i = end; i >= begin; i--) {
j = getDigit(arr[i], d);
bucket[count[j] - 1] = arr[i];
count[j]--;
}
7.最后将new出来的数组复制到原数组
代码如下(示例):
for (i = begin, j = 0; i <= end; i++, j++) {
arr[i] = bucket[j];
}
总代码
public class Code02_RadixSort {
// only for no-negative value
public static void radixSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
radixSort(arr, 0, arr.length - 1, maxbits(arr));
}
public static int maxbits(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
int res = 0;
while (max != 0) {
res++;
max /= 10;
}
return res;
}
public static void radixSort(int[] arr, int begin, int end, int digit) {
final int radix = 10;
int i = 0, j = 0;
int[] bucket = new int[end - begin + 1];
for (int d = 1; d <= digit; d++) {
int[] count = new int[radix];
for (i = begin; i <= end; i++) {
j = getDigit(arr[i], d);
count[j]++;
}
for (i = 1; i < radix; i++) {
count[i] = count[i] + count[i - 1];
}
for (i = end; i >= begin; i--) {
j = getDigit(arr[i], d);
bucket[count[j] - 1] = arr[i];
count[j]--;
}
for (i = begin, j = 0; i <= end; i++, j++) {
arr[i] = bucket[j];
}
}
}
public static int getDigit(int x, int d) {
return ((x / ((int) Math.pow(10, d - 1))) % 10);
}
}
总结
这个基数排序利用桶排序的思想,实现了很大的优化