Reputation: 65
I have an array of length X of number Strings ("32", "49", "2", ...) and I need to find the largest number in that array and return the location ( array[3] is the largest number)
is there a library like array[0].isLessThan(array[3])? or something similar?
program so far:
int max 0
for(i=1; i<X; i++){
if(array(max).isLessThan(array[i]))
max = i;
}
Upvotes: 0
Views: 3045
Reputation: 2136
A more complex solution for the sake of Acamedic interest :) :
public static void main(String[] args) {
String[] anArrayOfStrings={"199999","32", "33",
"10000","45","99999","72987","0","92"};
Test test=new Test();
Test.CX cx=test.new CX();
java.util.Arrays.sort(anArrayOfStrings,cx) ;
System.out.println("Item="+anArrayOfStrings[(anArrayOfStrings.length-1)]);
}
class CX<String> implements Comparator{
@Override
public int compare(Object arg0, Object arg1) {
if( Integer.parseInt((java.lang.String) arg0) >
Integer.parseInt((java.lang.String) arg1)){
return 1;
}else if(Integer.parseInt((java.lang.String) arg0) <
Integer.parseInt((java.lang.String) arg1)){
return -1;
}
return 0;
}
}
Upvotes: -1
Reputation: 25
This is my suggestion. Please correct me if Im wrong.
int max 0
for(i=0; i<X; i++){
if(array[i]).isLessThan(array[i+1]))
max = i+1;
else
max = i
}
Upvotes: 0
Reputation: 36
I would recommend casting the values to integers as you compare two values.
You will need to keep track of the max as well as the index. This solution assumes all values are non-negative (because I set max to -1), but you easily change max to int min or something like that.
int max = -1;
int index = -1;
for (int i = 0; i < array.Length; i++)
{
int value = Integer.parse(array[i]);
if (value > max)
{
max = value;
index = i;
}
}
At this point you have the index of the highest value in the array. If there are multiple max values, you could store an array of indices.
Upvotes: 2