I am attempting to return the two largest integers from my int array. I am able to return the largest and the smallest fine, but I cannot get my algorithm to return the two largest. Any help is greatly appreciated here.
Please forgive any errors in my code. This is a practice session and the question has been taken from last years exam material at university.
Here is my code:
public class TwoLargestIntsArray {
public static void main(String [] args){
int [] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
System.out.println(twoLargest(values));
System.out.println();
}
public static int twoLargest(int values[]){
int largestA = values[0];
int largestB = values[0];
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestA = values[i];
}
if(values[i] < largestA){
largestB = values[i];
}
}
return largestA + largestB;
}
}
You can write
OUTPUT:
1 = 25
2 = 20
If performance is not an issue here, which it shouldn't be on small arrays, this could be done with less code.
The most straightforward solution is to simply sort the array and return its last, and next to last value:
The time complexity of the above code is O(n log (n)), as stated in the Javadoc for
Arrays.sort()
:If expected input is an array with less than two elements, some error handling would need to be added, such as throwing an exception.
NB. We could use this astuce with any bean Object implementing comparable or by using a related custom comparator.
Try this out: