查找数组中的第二个最小整数.返回第二个最小整数的错误值 [英] Find the second smallest integer in an array. Returns wrong value for 2nd smallest integer

查看:61
本文介绍了查找数组中的第二个最小整数.返回第二个最小整数的错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Java在 array 中找到第二个最小的数字.我有以下代码.它可以工作,但是由于某种原因,它没有第二次完全通过数组来查找第二个最小值.它停在第三个索引处,并返回该值.如您所见,第二个最小值位于索引14处.我们将不胜感激.谢谢.

I need to find the second smallest number in an array using java. I have the following code. It sort of works but for some reason it does not go through the array a second time completely to find the second smallest value. It stops at the 3rd index and returns that value instead. As you can see the second smallest value is at index 14. Any help would be greatly appreciated. Thanks.

//Java程序查找数组中的第一个和第二个最小数字

// Java program to find first and second smallest number in an array

public class FindSmallest2 
    {
        public static void main(String[] args)
            {
                 int[] values;
                 values = new int[15];   
                 values[0]=341;            
                 values[1]=273;
                 values[2]=278;
                 values[3]=329;
                 values[4]=445;
                 values[5]=275;
                 values[6]=275;
                 values[7]=243;
                 values[8]=334;
                 values[9]=412;
                 values[10]=393;
                 values[11]=299;
                 values[12]=343;
                 values[13]=317;
                 values[14]=265;
                 int small1, small2;
                 small1 = small2 = values[0]; 
                 for(int i = 1; i < values.length; i++) 
                     {
                         if(values[i]<small1) 
                         {
                             small2 = small1;
                             small1 = values[i];
                         }
                     }
                         System.out.println("1st smallest value: "+small1);
                         System.out.println("2nd smallest value: "+small2);
          }
      }

推荐答案

您无需考虑以下情况:测试的数字 values [i] 不是最小的,但小于当前的第二个最小数字.

You don't account for the case in which the tested number values[i] is not the smallest, but it's smaller than the current 2nd smallest number.

这是一个可能的解决方法:

Here's a possible fix :

if (values[i]<small1) {
    small2 = small1;
    small1 = values[i];
} else if (values[i]<small2) {
    small2 = values[i];
}

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

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