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
-
2Do you want largest index or index of largest element ?Alekhya Vemavarapu– Alekhya Vemavarapu2015年04月15日 03:32:20 +00:00Commented Apr 15, 2015 at 3:32
-
index of largest elementtheUser– theUser2015年04月15日 03:33:42 +00:00Commented Apr 15, 2015 at 3:33
5 Answers 5
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
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;
}
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
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
Alekhya Vemavarapu Alekhya VemavarapuAlekhya Vemavarapu
1,1551 gold badge10 silver badges27 bronze badges
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
lang-java