|
|
@@ -5,22 +5,44 @@ package com.cyl.algorithrms.sort;
|
|
|
*/
|
|
|
public class Counting {
|
|
|
|
|
|
+ /**
|
|
|
+ * 排序
|
|
|
+ * @param a 待排序数组
|
|
|
+ * @param ascending 排序方向 true-升序,false-降序
|
|
|
+ */
|
|
|
public static void sort(int[] a, boolean ascending) {
|
|
|
+ //找到待排序数组中的最大元素值
|
|
|
int maxValue = getMaxValue(a);
|
|
|
+ //根据最大元素值创建辅助数组,因为数组是0基表示的,因此需要加1,才能使得数组的最大下标等于最大元素值
|
|
|
int[] aux = new int[maxValue + 1];
|
|
|
+ //遍历待排序数组,根据元素值,使得辅助数组相应应下标的元素值加1,从而记录有相同值的元素
|
|
|
+ // Java 中int类型的零值(初始值)是0
|
|
|
for(int v : a) {
|
|
|
aux[v]++;
|
|
|
}
|
|
|
+ // 根据排序方向 设置 排序时在原数组的元素放置顺序(数组下标变化方向)
|
|
|
+ // 升序 数组下标变化方向 从0 -> 数组长度-1
|
|
|
+ // 降序 数组下标变化方向 从数组长度-1 -> 0
|
|
|
+ // 用于指定当前可存放元素的数组下标
|
|
|
int ptr = ascending ? -1 : a.length;
|
|
|
int adder = ascending ? 1 : -1;
|
|
|
+ // 第一个循环:遍历辅助数组
|
|
|
for(int i=0; i < aux.length; i++) {
|
|
|
+ // 第二个循环:根据对应下标的辅助数组的元素值,表示存放的记录个数
|
|
|
for(int j=0; j < aux[i]; j++) {
|
|
|
+ // 移动
|
|
|
ptr = ptr + adder;
|
|
|
+ // 放置元素
|
|
|
a[ptr] = i;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 寻找数组中的最大值
|
|
|
+ * @param a 数组
|
|
|
+ * @return 数组中的最大值
|
|
|
+ */
|
|
|
public static int getMaxValue(int[] a) {
|
|
|
int maxValue = a[0];
|
|
|
for (int v : a) {
|