|
|
@ -4,11 +4,11 @@
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
package chapter_sorting;
|
|
|
|
package chapter_sorting;
|
|
|
|
|
|
|
|
|
|
|
|
import java.util.*;
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
|
|
public class radix_sort {
|
|
|
|
public class radix_sort {
|
|
|
|
/* 获取元素 num 的第 k 位,其中 exp = 10^(k-1) */
|
|
|
|
/* 获取元素 num 的第 k 位,其中 exp = 10^(k-1) */
|
|
|
|
static int digit(int num, int exp) {
|
|
|
|
static int digit(int num, int exp) {
|
|
|
|
// 传入 exp 而非 k 可以避免在此重复执行昂贵的次方计算
|
|
|
|
// 传入 exp 而非 k 可以避免在此重复执行昂贵的次方计算
|
|
|
@ -49,12 +49,12 @@
|
|
|
|
for (int num : nums)
|
|
|
|
for (int num : nums)
|
|
|
|
if (num > ma) ma = num;
|
|
|
|
if (num > ma) ma = num;
|
|
|
|
// 按照从低位到高位的顺序遍历
|
|
|
|
// 按照从低位到高位的顺序遍历
|
|
|
|
|
|
|
|
for (int exp = 1; ma >= exp; exp *= 10)
|
|
|
|
|
|
|
|
// 对数组元素的第 k 位执行「计数排序」
|
|
|
|
// k = 1 -> exp = 1
|
|
|
|
// k = 1 -> exp = 1
|
|
|
|
// k = 2 -> exp = 10
|
|
|
|
// k = 2 -> exp = 10
|
|
|
|
// k = 3 -> exp = 100
|
|
|
|
// k = 3 -> exp = 100
|
|
|
|
// 即 exp = 10^(k-1)
|
|
|
|
// 即 exp = 10^(k-1)
|
|
|
|
for (int exp = 1; ma >= exp; exp *= 10)
|
|
|
|
|
|
|
|
// 对数组元素的第 k 位执行「计数排序」
|
|
|
|
|
|
|
|
countSort(nums, exp);
|
|
|
|
countSort(nums, exp);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
@ -64,5 +64,4 @@
|
|
|
|
radixSort(nums);
|
|
|
|
radixSort(nums);
|
|
|
|
System.out.println("基数排序完成后 nums = " + Arrays.toString(nums));
|
|
|
|
System.out.println("基数排序完成后 nums = " + Arrays.toString(nums));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|