theUser
theUser

Reputation: 91

Index of Highest element in an array

I have a method called "indexOfMaxInRange", and I built most of the code, but, I feel like something is off. The goal is to traverse an array, and return the index of highest element in the array. Here is the code

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;}

I have things set up, for the most part, I feel like there just needs to be more polishing, and a few edits in the code. Any suggestions?

Upvotes: 0

Views: 346

Answers (5)

Mohsen Bahaloo
Mohsen Bahaloo

Reputation: 287

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;
}

Upvotes: 0

Alekhya Vemavarapu
Alekhya Vemavarapu

Reputation: 1155

consider the following code:

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

Upvotes: 0

user4668606
user4668606

Reputation:

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;

}

Upvotes: 1

N Kaushik
N Kaushik

Reputation: 2208

maybe this will work to find the index of largest element

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;
}

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

How about this:

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;
}

Upvotes: 0

Related Questions