Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the two largest integers in an array of values

Tags:

java

arrays

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; 
}

}
like image 272
PrimalScientist Avatar asked May 05 '13 12:05

PrimalScientist


People also ask

How do you find the largest integer in an array?

To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.


2 Answers

You can write

public static int[] twoLargest(int values[]){
    int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;

    for(int value : values) {
        if(value > largestA) {
            largestB = largestA;
            largestA = value;
        } else if (value > largestB) {
            largestB = value;
        }
    }
    return new int[] { largestA, largestB }; 
}
like image 77
Peter Lawrey Avatar answered Sep 18 '22 13:09

Peter Lawrey


public static void twoLargest(int values[]){

    int largestA = values[0];
    int largestB = -1;

    for(int i = 0; i < values.length; i++){

            if(values[i] > largestA){
                largestB = largestA;
                largestA = values[i];
            }
            else if (values[i] > largestB && values[i] != largestA) {
                largestB = values[i];
            }
    }
    System.out.println("Largest - " + largestA);
    System.out.println("2nd largest Largest - " + largestB);
}
like image 45
Sagar Waghmare Avatar answered Sep 17 '22 13:09

Sagar Waghmare