在一个数组的Java查找最小和第二小值 [英] Finding the smallest and second smallest value in an array Java

查看:197
本文介绍了在一个数组的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.

我已经写了两个这样的

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.

任何想法?谢谢!

推荐答案

是这样的:

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

这篇关于在一个数组的Java查找最小和第二小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆