包含最大值的数组中元素的位置

时间:2016-11-12 20:37:17

标签: java

我怎么知道阵列中最大值的位置,我知道最大值,但我需要知道它的位置。

class maximumofarray
{

    public static void main(String[] args)
    {
    double maximum;
    int i;
    double [] a={1.5,2.3,4.2,-9.4,2.0,12.9,-5.0,12.9,-0.1,-15.0,0.0};
    maximum=a[0];
    for (i = 1; i <= 10; i++) 
      {
      if (a[i] > maximum)
        {
        maximum = a[i];
        }

      }
    System.out.println("The maximum element is "+maximum);

    }
}

3 个答案:

答案 0 :(得分:2)

您需要按照以下步骤操作:

(1)声明另一个变量(maxLocation),它是收集maximum

的位置所必需的

(2)当您指定最大值(即a[i] > maximum)时,还会将最大元素的位置收集为maxLocation

该守则如下:

double maximum;
int i;
int maxLocation =0;
double [] a={1.5,2.3,4.2,-9.4,2.0,12.9,-5.0,12.9,-0.1,-15.0,0.0};
maximum=a[0];
for (i = 1; i <= 10; i++) 
  {
  if (a[i] > maximum)
    {
       maximum = a[i]; //assign maximum value
       maxLocation = i; //Also, collect the location as well to maxLocation
    }

  }
System.out.println("The maximum element is "+maximum);
System.out.println("The maximum element is "+maxLocation);

}

答案 1 :(得分:1)

使用第二个变量......

double maximum;
int locationOfMaximum;
int i;
double [] a={1.5,2.3,4.2,-9.4,2.0,12.9,-5.0,12.9,-0.1,-15.0,0.0};
maximum=a[0];
locationOfMaximum = 0;
for (i = 1; i <= 10; i++) 
  {
  if (a[i] > maximum)
    {
    maximum = a[i];
    locationOfMaximum = i;
    }

  }
System.out.println("The maximum element is "+maximum+";  it appears at index "+locationOfMaximum);

为了记录,我还建议进行一些更改,以使代码更具可读性......

double [] a={1.5,2.3,4.2,-9.4,2.0,12.9,-5.0,12.9,-0.1,-15.0,0.0};

double maximum = Double.MIN_VALUE;  // Or Double maximum = null;
int locationOfMaximum = -1;
for (int i = 0; i < a.length; i++) {
  if (a[i] > maximum) {
    maximum = a[i];
    locationOfMaximum = i;
  }

}
System.out.println("The maximum element is "+maximum+";  it appears at index "+locationOfMaximum);

答案 2 :(得分:0)

您可以使用utilit方法Arrays.sort(a)对数组进行排序。那么max元素将保持lat指数。

double maximum;
int i;
double [] a={1.5,2.3,4.2,-9.4,2.0,12.9,-5.0,12.9,-0.1,-15.0,0.0};

Arrays.sort(a);

System.out.println("The maximum element is "+a[a.length-1]);