【发布时间】:2015-04-09 18:49:48
【问题描述】:
我试图通过使用两个简单的for 循环来找到ArrayList 中的最小整数。我最初尝试使用一个for 循环,但它没有正确更新。我还没有学过collections,所以应该不用collections代码来完成。
这就是我所拥有的:
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) 以查看发生了什么,它似乎更新了不同的值,最后,最后一个值。我不知道为什么会这样。
这是它正在打印的示例:
Original list:
[47, 19, 46, 42, 15, 26, 36, 27, 13, 15, 1, 40, 34, 14, 6, 34, 28, 12, 15, 13]
Print the minimum:
1 1 1 1 1 1 1 1 1 1 1 6 6 6 6 12 12 12 15 13
【问题讨论】:
-
你不需要双循环。只要你保持当前的最小值,单循环就应该这样做
-
对arraylist排序并返回索引为0的元素?
-
@gtgaxiola,如果我用一个循环尝试它,我会在我的
if语句中比较什么?因为我尝试了一段时间,但它也没有给我正确的最小值。 -
你保留一个临时变量来存储当前最小值。
-
对于所有起始索引
i,您的代码当前成功地找到了从i开始的列表中的最小编号。您只想找到从0开始的列表中最小的数字。