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?

Alekhya Vemavarapu
1,1551 gold badge10 silver badges27 bronze badges
asked Apr 15, 2015 at 3:29
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;
}
answered Apr 15, 2015 at 3:37
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;

}

answered Apr 15, 2015 at 3:37
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;
}
answered Apr 15, 2015 at 3:32
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;
answered Apr 15, 2015 at 3:35
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;
}
Mayank Jain
5,7547 gold badges35 silver badges67 bronze badges
answered Apr 15, 2015 at 5:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.