You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化Java基数排序:数组无变化时终止循环并输出结果

基数排序优化:提前终止无变化的迭代

要实现“数组排序迭代中不再变化时终止循环”的优化,需要修改以下3个核心位置:

1. 修改countingSort方法的返回值

原方法为void类型,改为返回boolean,用来标识本次排序是否导致数组发生变化:

  • 返回true表示数组因本次排序产生了变动
  • 返回false表示排序后数组与原数组完全一致

2. 在countingSort中添加数组相等判断逻辑

生成outputArray后,先对比它与原inputArray的内容:

  • 若完全一致,直接返回false,无需执行数组复制操作
  • 若不一致,将outputArray复制到inputArray后返回true

3. 修改radixSort的循环终止条件

原循环固定执行d次(最大元素的位数),现在每次调用countingSort后检查返回值:如果返回false(数组无变化),立即跳出循环,停止后续迭代。


修改后的完整代码

import java.util.Arrays;

public class RadixSort {

    // 修改返回值为boolean,标识数组是否发生变化
    boolean countingSort(int inputArray[], int size, int place) {
        // 找出输入数组中对应位权的最大元素
        int k = ((inputArray[0] / place) % 10);
        for (int i = 1; i < size; i++) {
            if (k < ((inputArray[i] / place) % 10)) {
                k = ((inputArray[i] / place) % 10);
            }
        }
        // 初始化计数数组
        int count[] = new int[k + 1];
        Arrays.fill(count, 0);
        // 统计对应位的出现次数
        for (int i = 0; i < size; i++) {
            count[((inputArray[i] / place) % 10)]++;
        }
        // 计算计数数组的累积和
        for (int i = 1; i < (k + 1); i++) {
            count[i] += count[i - 1];
        }
        // 生成输出数组
        int outputArray[] = new int[size];
        for (int j = (size - 1); j >= 0; j--) {
            outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
            count[(inputArray[j] / place) % 10]--;
        }

        // 核心判断:数组是否未发生变化
        if (Arrays.equals(inputArray, outputArray)) {
            return false;
        }
        // 数组有变化则复制结果
        System.arraycopy(outputArray, 0, inputArray, 0, size);
        System.out.println(Arrays.toString(inputArray));
        return true;
    }

    void radixSort(int inputArray[], int size) {
        // 找出输入数组的最大元素
        int max = inputArray[0];
        for (int i = 1; i < size; i++) {
            if (max < inputArray[i]) {
                max = inputArray[i];
            }
        }
        // 计算最大元素的位数
        int d = 0;
        int tempMax = max;
        while (tempMax > 0) {
            d++;
            tempMax /= 10;
        }
        // 执行计数排序,增加提前终止逻辑
        int place = 1;
        for (int i = 0; i < d; i++) {
            System.out.print("iteration no = " + (i+1) + " ");
            boolean changed = countingSort(inputArray, size, place);
            if (!changed) {
                System.out.println("数组无变化,提前终止循环");
                break;
            }
            place *= 10;
        }
    }
}

内容的提问来源于stack exchange,提问作者JetaimeA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:09:25