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

插入排序与值打印:代码无法通过测试用例的问题求助

问题修复方案

你的代码核心问题是排序方向与方法要求不符:sortAndPrintReverse需要实现降序排序,但当前代码是升序插入排序,同时可能存在打印时机不符合测试预期的情况,以下是具体修复方案:

1. 修正排序逻辑(核心修复)

原代码中temp.compareTo(arr[possibleIndex - 1]) < 0的判断是将更小的元素往前移动,实现升序排序。要改成降序,只需将比较条件改为temp.compareTo(arr[possibleIndex - 1]) > 0,让更大的元素往前移动。

2. 调整打印时机(根据测试需求选择)

情况A:测试要求排序完成后仅打印最终降序数组

将打印代码移到排序循环外部,只输出最终结果:

public class U7_L6_Activity_One {
  public static void sortAndPrintReverse(String [] arr) {
    // 降序插入排序
    for (int j = 1; j < arr.length; j++) {
      String temp = arr[j];
      int possibleIndex = j;
      // 修正为降序判断条件
      while (possibleIndex > 0 && temp.compareTo(arr[possibleIndex - 1]) > 0) {
        arr[possibleIndex] = arr[possibleIndex - 1];
        possibleIndex--; 
      }
      arr[possibleIndex] = temp;
    }
    // 排序完成后打印最终数组
    for (String str : arr) {
      System.out.print(str + " ");
    }
    System.out.println();
  }
}

情况B:测试要求打印每一步排序过程

保留内部打印逻辑,仅修正排序方向即可:

public class U7_L6_Activity_One {
  public static void sortAndPrintReverse(String [] arr) {
    for (int j = 1; j < arr.length; j++) {
      String temp = arr[j];
      int possibleIndex = j;
      // 修正为降序判断条件
      while (possibleIndex > 0 && temp.compareTo(arr[possibleIndex - 1]) > 0) {
        arr[possibleIndex] = arr[possibleIndex - 1];
        possibleIndex--; 
      }
      arr[possibleIndex] = temp;
      // 每步插入后打印当前数组状态
      for (String str : arr) {
        System.out.print(str + " ");
      }
      System.out.println();
    }
  }
}

验证说明

  • 降序排序的核心是调整插入排序的比较逻辑,确保更大的字符串被优先放到数组前端(基于String.compareTo()的字典序规则)。
  • 若测试用例仍不通过,可检查是否需要处理空数组或单元素数组的边界情况(当前代码已兼容这类场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:01:43