【问题标题】:sorting algorithm problem in Java; get wrong resultsJava中的排序算法问题;得到错误的结果
【发布时间】:2020-08-25 16:48:50
【问题描述】:

MainProgram 类中创建一个名为indexOfSmallestFrom 的类方法。它的工作方式与上一节中的方法类似,但只考虑来自某个索引的表值。除了表之外,它还接收这个起始索引作为参数。

在本例中,第一个方法调用从索引 0 开始搜索最小数字的索引。从索引 0 开始,最小数字为 -1,其索引为 0。第二个方法调用搜索从索引 1 开始的最小值。在这种情况下,最小的数字是 6,它的索引是 1。第三次调用从索引 2 开始搜索最小值的索引。那么最小的数字是 8,它的索引是 3。

应该为最小的数组打印索引。 根据int数组,我的输出应该是:

1
1
4

但我明白了:

1
1
3

无法从逻辑上弄清楚,为什么。

public class MainProgram {

    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};
        
        System.out.println(MainProgram.indexOfSmallestFrom(array, 0));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 1));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 2));
    }
    
    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int count = startIndex;
        int indexOf = 0;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               count++;
            }
              indexOf = count; 
        }
            return indexOf;
    }   
 
}

【问题讨论】:

  • 不应该设置indexOf 只在遇到新的最小数字时发生?您可能需要检查indexOf = count; 的逻辑位置
  • 或者您可以在找到新的最小项目时保存变量“I”,然后您不必使用“count”。
  • 您的逻辑错误是您现在实际上返回 startindex + 在子数组中找到新最小值的次数(- 1 因为您分配了变量 minimum)。

标签: java arrays algorithm sorting


【解决方案1】:

当你发现一个元素小于 indexOf 初始初始化为 startIndex 的值时,只需更新 indexOf。

遍历所有值后...返回最终更新的 indexOf。

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};

        System.out.println(indexOfSmallestFrom(array, 0));
        System.out.println(indexOfSmallestFrom(array, 1));
        System.out.println(indexOfSmallestFrom(array, 2));
    }

    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int indexOf = startIndex;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               indexOf = i;
            }
        }
            return indexOf;
    }   
}

【讨论】:

  • 非常感谢。这就是我想太多的结果。
  • @FrancisAdewale 你能给我你的第一票吗?
  • @YashShah Lol 我认为他错误地否决了你 xD
  • @saurabhgupta 要投反对票,必须至少有 125 个代表点。
  • @YashShah 是的,我的错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 2014-03-14
相关资源
最近更新 更多