Java计数排序

/**
 * 计数排序
 *
 * @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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值