java—使用简化的气泡式排序对数字进行排序不会返回第二小的值

igetnqfo  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(303)

在这段代码中,我需要找到第一个和第二个最小的生成数,我还需要找到总和。到目前为止,除了找到第二小的数字,我什么都做了。如何确保第二小的数字与最小的不同?

String str = JOptionPane.showInputDialog("How many iterations?");
int iter = Integer.parseInt(str);
String str2 = JOptionPane.showInputDialog("What is the max in our range?");
int max = Integer.parseInt(str2);
String str3 = JOptionPane.showInputDialog("What is the minimum in our range?");
int min = Integer.parseInt(str3);
int numcache = max;
int numcache1 = max;

int sum = 0;

for (int a = 0; a <= (iter - 1); a = a + 1) {
    double out;

    out = Math.round(Math.random() * (max - min + 1) + min);
    int output = (int) out;
    System.out.println(output);

    if (output < numcache) {
        numcache = output;
    }

    if (numcache < numcache1) {
        numcache1 = numcache;
    }

    sum = output + sum;

}
System.out.println("The 2nd smallest number is  " + numcache1);
System.out.println("The sum is " + sum);
System.out.println("The smallest number  is " + numcache);

这里是输出,输入20;10; 1

4
    4
    8
    10
    2
    10
    10
    7
    2
    9
    7 
    8
    1
    10
    7
    6
    8
    4
    8
    6
    The 2nd smallest number is  1
    The sum is 131
    The smallest number  is 1
bakd9h0s

bakd9h0s1#

改变 if 条件如下

if (output < numcache) {
    numcache1 = numcache;
    numcache = output;
}
else if (output < numcache1) {
    numcache1 = output;
}

true 在这种情况下,它将交换第1最小到第2,因为我们发现较小的数字比第一小。
false 在这种情况下,它将只检查第二小的数字。

sdnqo3pr

sdnqo3pr2#

你的逻辑是错误的。对于输出数据:当输出为“1”时,它比前一个“2”小。所以numcache是1。接下来检查numcache是否小于numcache1。这也是正确的,因为numcache现在是“1”(最小值),numcache1是“2”。所以numcache1也被设置为“1”。
解决方案:如果numcache1总是必须大于numcache,您可以这样做:

if (numcache + 1 < numcache1) {
    numcache1 = numcache;
}

相关问题