【发布时间】: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