我试图仅通过使用两个简单的 for
循环来查找 ArrayList
中的最小整数。我最初尝试使用一个 for
循环,但它没有正确更新。我还没有学习集合
,所以这应该在不使用任何集合
代码的情况下完成。
这就是我所拥有的:
public static void printInOrder(ArrayList<Integer> data){
int minIndex = 0 ;
for(int i = 0; i < data.size(); i++){
minIndex = i;
for(int j = i + 1; j < data.size() - 1; j++){
if(data.get(j) < data.get(minIndex)){
minIndex = j;}
}
System.out.println(data.get(minIndex) + " ");
}
}//printInOrder
我的最小值似乎总是列表中的最后一个值,因此我尝试在第一个 for
循环中打印 data.get(minIndex)
来看看会发生什么,它似乎更新了不同的值,最后更新了最后一个值。我不知道为什么会发生这种情况。
这就是它打印的内容:
原始列表:
[47, 19, 46, 42, 15, 26, 36, 27, 13, 15, 1, 40, 34, 14, 6, 34, 28, 12, 15, 13]
打印最小值:
1 1 1 1 1 1 1 1 1 1 1 6 6 6 6 12 12 12 15 13
最佳答案
如果您想避免使用集合,可以执行此快速解决方案。
public static void printInOrder(ArrayList<Integer> data){
Integer[] array = (Integer[]) data.toArray();
Arrays.sort(array);
System.out.println(array[0]);
}
在这种情况下,最小整数始终位于索引 0 处。
或者,如果您确实想使用循环遍历整个 ArrayList,我建议您将实际值存储在变量而不是索引中。这样做,你会得到:
public static void printInOrder(ArrayList<Integer> data){
int minInteger = data.get(0);
for(int i = 1; i < data.size(); i++){
if(data.get(i) < minInteger) minInteger= data.get(i);
}
System.out.println(minInteger);
}
关于java - 在没有集合的ArrayList中查找最小整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29546599/