0

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?

2
  • 2
    Do you want largest index or index of largest element ? Commented Apr 15, 2015 at 3:32
  • index of largest element Commented Apr 15, 2015 at 3:33

5 Answers 5

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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;

}

Comments

0

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

Comments

0

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;

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.