/**
* 计数排序
*
* @author 小流慢影
* @date 2023年5月5日
*/
public class CountSort {
public static void main(String[] args) {
int[] oldArray = {5, 4, 3, 1, 2, 13, 12, 115, 10, 11, 9, 7, 8, 6, 3, 5};
System.out.println("原数组:" + Arrays.toString(oldArray));
int[] newArray = countSort(oldArray);
System.out.println("排序后数组:" + Arrays.toString(newArray));
}
/**
* 计数排序
*
* @param oldArray 老数组
* @return 新数组
*/
private static int[] countSort(int[] oldArray) {
// 创建计数数组,因为要给数组内每个值计数,所以创建的计数数组长度为老数组的最大值+1,因为数组值可能为0,所以要+1
int maxValue = getMaxValue(oldArray);
int countArrayLength = maxValue + 1;
int[] countArray = new int[countArrayLength];
// 遍历老数组,给值计数
for (int countIndex : oldArray) {
countArray[countIndex] = countArray[countIndex] + 1;
}
// 新数组的下标,从头开始
int newIndex = 0;
// 创建新数组
int[] newArray = new int[oldArray.length];
// 遍历计数数组,从头开始,最前面的肯定是最小的,最后面的是最大的
for (int countIndex = 0; countIndex < countArray.length; countIndex++) {
int countValue = countArray[countIndex];
// 只有大于0才说明有值,才可以放入新数组,计数数组有多少计数就放进新数组多少次,同时新数组下标向后移
while (countValue > 0) {
newArray[newIndex] = countIndex;
newIndex++;
countValue--;
}
}
return newArray;
}
/**
* 获取最大的值
*
* @param oldArray 老数组
* @return 最大值
*/
private static int getMaxValue(int[] oldArray) {
int maxValue = oldArray[0];
for (int value : oldArray) {
if (maxValue < value) {
maxValue = value;
}
}
return maxValue;
}
}
Java计数排序
最新推荐文章于 2023-11-17 18:06:54 发布