[英]Finding minimum integer in ArrayList without collections
I'm trying to find the smallest integer in an ArrayList
just by using two simple for
loops. 我试图通过使用两个简单的
for
循环来查找ArrayList
的最小整数。 I tried originally with one for
loop, but it wasn't updating correctly. 我最初尝试使用一个
for
循环,但未正确更新。 I haven't learned collections
yet, so this should be done without using any collections
code. 我还没有学过
collections
,所以应该在不使用任何collections
代码的情况下完成。
This is what I have: 这就是我所拥有的:
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
My minimum always seems to be the last value in the list, so I tried printing the data.get(minIndex)
in the first for
loop to see what happens, and it seems to update it different values, and then finally, the last value. 我的最小值似乎始终是列表中的最后一个值,因此我尝试在第一个
for
循环中打印data.get(minIndex)
以查看会发生什么,并且似乎将其更新为不同的值,然后最后更新了最后一个值。 I have no idea why this is happening. 我不知道为什么会这样。
This is what it's printing for example: 例如,这是打印的内容:
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
You can do this quick solution if you want to avoid using Collections. 如果要避免使用“收藏夹”,可以执行此快速解决方案。
public static void printInOrder(ArrayList<Integer> data){
Integer[] array = (Integer[]) data.toArray();
Arrays.sort(array);
System.out.println(array[0]);
}
The smallest integer would always be at index 0 in this case. 在这种情况下,最小整数将始终位于索引0处。
Or, if you do want to go through the whole ArrayList using a loop, I'd suggest you store the actual value in a variable instead of the index. 或者,如果您确实想使用循环遍历整个ArrayList,建议您将实际值存储在变量而不是索引中。 Doing so, you get:
这样做,您将获得:
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);
}
You're not supposed to do sorting to find the minimum 您不应该进行排序以找到最小值
Here's the code 这是代码
public static void Min(int arr[])
{
int min = arr[0];
int i=0;
while(i<arr.length)
{
if (arr[i] < min) {
min=arr[i];
}
}
return min;
}
Untested: 未经测试:
public static int calculateMinIndex(final ArrayList<Integer> data) {
int minIndex = 0;
for(int i = 0; i < data.size() - 1; i++) {
if(data.get(i) > data.get(i+1)) {
minIndex = i+1;
}
}
return minIndex;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.