Reputation: 91
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
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
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
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
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
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