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

求助:修改Java归并排序程序以支持指定子数组排序

修改归并排序以支持指定子数组排序

问题分析

你需要修改归并排序程序,仅对命令行传入的起始-结束索引区间内的子数组进行排序,其余元素保持原顺序。原代码存在两个核心问题:

  1. 错误使用StdIn.readAllStrings()读取输入,实际命令行参数包含索引和单词列表,需直接解析args数组
  2. 当前sort方法默认排序整个数组,未支持指定区间

解决方案代码

import java.util.Arrays;

public class MergeSort {
    // 排序整个数组的方法(保留原功能)
    public static void sort(Comparable[] a) {
        Comparable[] aux = new Comparable[a.length];
        sort(a, aux, 0, a.length);
    }

    // 排序指定[lo, hi)区间的私有方法(原逻辑不变)
    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
        if (hi - lo <= 1) return;
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid, hi);
        
        // 归并操作
        int i = lo, j = mid;
        for (int k = lo; k < hi; k++) {
            if (i == mid) aux[k] = a[j++];
            else if (j == hi) aux[k] = a[i++];
            else if (a[j].compareTo(a[i]) < 0) aux[k] = a[j++];
            else aux[k] = a[i++];
        }
        
        // 把归并结果写回原数组
        for (int k = lo; k < hi; k++) {
            a[k] = aux[k];
        }
    }

    // 新增:排序指定[start, end]闭区间的方法
    public static void sortSubarray(Comparable[] a, int start, int end) {
        if (start < 0 || end >= a.length || start > end) {
            throw new IllegalArgumentException("Invalid index range");
        }
        Comparable[] aux = new Comparable[a.length];
        sort(a, aux, start, end + 1); // 转换为原方法的[lo, hi)开区间
    }

    public static void main(String[] args) {
        // 解析命令行参数:前两个是起始、结束索引,后面是单词列表
        int start = Integer.parseInt(args[0]);
        int end = Integer.parseInt(args[1]);
        String[] a = Arrays.copyOfRange(args, 2, args.length);

        // 仅排序指定区间
        sortSubarray(a, start, end);

        // 输出结果
        for (String word : a) {
            System.out.print(word + " ");
        }
        System.out.println();
    }
}

关键改动说明

  1. 命令行参数处理:

    • 从args数组直接提取索引:args[0]是起始索引,args[1]是结束索引
    • 用Arrays.copyOfRange提取从索引2开始的单词列表,生成待排序数组
  2. 指定区间排序:

    • 新增sortSubarray方法,接受闭区间[start, end],内部转换为原归并排序的开区间[start, end+1](因为原方法的hi是不包含的边界)
    • 增加了简单的索引合法性校验,避免非法输入
  3. 输出调整:

    • 替换StdOut为标准System.out(如果你的环境依赖StdOut,可改回,但标准Java环境用System.out更通用)

测试用例验证

  • 测试用例1:
    执行命令:java MergeSort 2 4 toy apply sand bay cat dog fish
    程序会排序索引2-4的元素(sand、bay、cat),排序后变为bay、cat、sand,最终输出:toy apply bay cat sand dog fish
  • 测试用例2:
    执行命令:java MergeSort 0 3 was had him and you his the but
    排序索引0-3的元素(was、had、him、and),排序后变为and、had、him、was,最终输出:and had him was you his the but

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:15:44