简体   繁体   English

在数组中查找 max 和 min 的索引

[英]finding the index of max and min in an array

This is my code.这是我的代码。 I am using the bluej IDE.我正在使用 bluej IDE。

    public class practice
    {
public int[] minMax(int[] num) {  
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
    if (num[i] < smallest) smallest = num[i];
    if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
    if (num[i] != smallest) countsmall++;
    if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}

I am trying to find the minimum and maximum value in an array which I successfully did.我试图在我成功完成的数组中找到最小值和最大值。 After that,I am trying to find its index.之后,我试图找到它的索引。 I created a variable count, and then went through the array.我创建了一个变量计数,然后遍历了数组。 If that item in the array does not equal the minimum or maximum value, count+= count.如果数组中的该项不等于最小值或最大值,则 count+= count。 However, for some reason its not working.但是,由于某种原因,它不起作用。 The code compiles but returns the wrong value.代码编译但返回错误的值。 Keep in mind I am not allowed to use java libraries.请记住,我不允许使用 java 库。 Any help would be much appreciated, thanks.任何帮助将不胜感激,谢谢。

If you want also indexes of biggest and smallest, why dont you do it in one loop?如果您还想要最大和最小的索引,为什么不在一个循环中执行呢? eg:例如:

public class practice
{
    public int[] minMax(int[] num) {  
      int smallest = num[0];
      int largest = num[0];
      int countsmall = 0;
      int countlarge = 0;
      for (int i = 0; i < num.length; i++){
        if (num[i] < smallest) {
            smallest = num[i];
            countsmall=i;
        }
        if (num[i] > largest) {
            largest = num[i];
            countlarge=i;
        }
      }
    
      int array[] = {countsmall,countlarge};
      return array;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM