Supernaturalgirl 1967
Supernaturalgirl 1967

Reputation: 289

Finding the smallest and second smallest value in an array Java

I'm trying to create two method one that finds the smallest and one that finds the second smallest value in an Array of objects.

I've written the two like this

public static BanffMarathonRunner getFastestTime(BanffMarathonRunner[] runner){
    if(runner.length == 0){
        return null;
    }
    BanffMarathonRunner fastest = runner[0];
    for(int i = 0; i< runner.length; i++){
        BanffMarathonRunner now = runner[i];
        if(now.Time < fastest.Time){
            fastest = now;

        }
    }
    return fastest;
}
    public static BanffMarathonRunner getSecondFastestTime(BanffMarathonRunner[] runner){
        if(runner.length == 0){
            return null;
        }
        BanffMarathonRunner fastest = runner[0];
        BanffMarathonRunner secondFastest = runner[0];
        for(int i = 0; i< runner.length; i++){
            BanffMarathonRunner now = runner[i];
            if(now.Time < fastest.Time){
                fastest = now;
        for(int j = 0; j< runner.length; j++){
            BanffMarathonRunner now2 = runner[j];
            if(now2.Time < secondFastest.Time){

                secondFastest = now2;
                if(now2.Time == fastest.Time){
                    secondFastest = secondFastest;
                }
            }
        }

            }
        }
        return secondFastest;
    }

I've figured out the how to find the smallest value, I just need to find the second smallest and I'm not sure how.

Any Ideas? Thanks!

Upvotes: 1

Views: 1517

Answers (3)

Andrew Luo
Andrew Luo

Reputation: 927

something like this:

findSecondSmallest anArray[]:
    if anArray.length < 2:
        return null;
    fastest = anArray[0];
    secondFastest = anArray[1];
    if fastest > secondFastest:
        fastest = anArray[1];
        secondFastest = anArray[0]
    for each element in anArray:
        if element < fastest:
            secondFastest = fastest;
            fastest = element;
        else if element < secondFastest:
            secondFastest = element;

    return secondFastest

Upvotes: 0

Srinivasu
Srinivasu

Reputation: 1235

Arrays.sort(test);
   if(test.length-2 >= 0)
       System.out.println(test[test.length-2]);

Upvotes: 1

Wajahat
Wajahat

Reputation: 1633

Once you know the fastest runner, store the index of this entry. Then when finding the 2nd fastest runner, ignore the index of Fastest runner in the loop using 'continue'

Also for any K-smallest entry, you can see the idea given on this question: K smallest in Array Java

Upvotes: 0

Related Questions