algo/java/13_sorts/RadixSort.java
2019-07-25 15:06:00 +08:00

63 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @Description:基数排序
* @Author: Hoda
* @Date: Create in 2019-07-25
* @Modified By:
* @Modified Date:
*/
public class RadixSort {
/**
* 基数排序
*
* @param arr
*/
public static void radixSort(int[] arr) {
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
// 从个位开始对数组arr按"指数"进行排序
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}
/**
* 计数排序-对数组按照"某个位数"进行排序
*
* @param arr
* @param exp 指数
*/
public static void countingSort(int[] arr, int exp) {
if (arr.length <= 1) {
return;
}
// 计算每个元素的个数
int[] c = new int[10];
for (int i = 0; i < arr.length; i++) {
c[(arr[i] / exp) % 10]++;
}
// 计算排序后的位置
for (int i = 1; i < c.length; i++) {
c[i] += c[i - 1];
}
// 临时数组r存储排序之后的结果
int[] r = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
r[c[(arr[i] / exp) % 10] - 1] = arr[i];
c[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < arr.length; i++) {
arr[i] = r[i];
}
}
}