数组中最高元素的索引

时间:2015-04-15 03:30:00

标签: java arrays sorting

我有一个名为“indexOfMaxInRange”的方法,我构建了大部分代码,但是,我觉得有些东西是关闭的。目标是遍历一个数组,并返回数组中最高元素的索引。这是代码

public static int indexOfMaxInRange(int[] a,int low, int high)
    {int[] count=a;int index=0;
    for(int i=0;i<count.length;i++)
        {if(a[i]>low&&a[i]<high)index++;}
return index;}

我设置的东西,在大多数情况下,我觉得只需要更多的抛光,并在代码中进行一些编辑。有什么建议吗?

5 个答案:

答案 0 :(得分:1)

也许这可以找到最大元素的索引

public static int indexOfMaxInRange(int[] a,int low, int high)
{
    int index=-1;
    int max=0;
    for(int i=0;i<a.length;i++)
    {if(a[i]>max)
       {
         max=a[i];
         index=i;
        }
     } 
    return index;
}

答案 1 :(得分:1)

public static int indexOfMaxInRange(int[] a , int low , int high){
    if(high >= a.length)
        throw new IllegalArgumentException("High must be smaller than arraylength");
    if(low < 0)
        throw new IllegalArgumentException("Low must be > 0");
    if(low > high)
        throw new IllegalArgumentException("Low must be > High");

    if(a.length == 0)
        return -1;

    int index = low;
    for(int i = low ; i < high ; i++)
        if(a[index] < a[i])
            index = i;

    return index;

}

答案 2 :(得分:0)

这个怎么样:

public static int indexOfMaxInRange(int[] a) {
    int index=0;
    int largest=0;
    for (int i=0; i < a.length; ++i) {
        if (a[i] > largest) {
            largest = a[i];
            index = i;
        }
    }

    return index;
}

答案 3 :(得分:0)

考虑以下代码:

int largest = 0, index = 0;  
for (int i = 1; i < array.length; i++) {  
  if ( array[i] >= largest ) {  
      largest = array[i];  
      index = i;  
   }  
}
return index;

答案 4 :(得分:0)

public static int indexOfMax(int[] arr) {
int index=0;
int max=0;
for (int i=0; i < arr.length; i++) {
    if (arr[i] > max) {
        max = arr[i];
        index = i;
    }
}

return index;
}
相关问题