在数组中查找min元素 [英] Finding min element in an array

查看:83
本文介绍了在数组中查找min元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试代码以找到数组中的min和max元素。我的代码可以找到最大值,但是我的min打印出数组中的Minimum元素:0。我可能犯了一个小错误,使我大笑。

Testing out code to find the min and max element in an array. My code for finding the maximum works fine .. but my min prints "Minimum element in the array: 0". I probably have one little mistake that is throwing me off lol.

 public void deleteMin() {

  // set value for comparision starting from the beginning of the array
  int arrayMin = arr[0];

  for (int j = 0; j < nElems; j++) {
     if (arr[j] < arrayMin) {
        arrayMin = arr[j];
     }
    // insert delete functionality    
  } 
  System.out.println("Minimum element in the array: " + arrayMin);
}


推荐答案

您的代码正确无误现在站着。代码完成后, arrayMin 包含0的唯一原因是

Your code is correct as it stands now. The only reason for arrayMin to contain 0 after the code has finished is if


  • nElems 没有设置为 arr.length ,或者

  • 0确实是

  • nElems was not set to arr.length, or
  • 0 was indeed the smallest element in the array.

可以简化代码。

Java 8

int arrayMin = IntStream.of(arr).min().getAsInt();

Java 7

int arrayMin = arr[0];
for (int i : arr)
    arrayMin = Math.min(arrayMin, i);

(请注意,两个解决方案均假定为非空数组,否则将无法定义min。)

(Note that both solutions assume a non-empty array since min would otherwise be undefined.)

这篇关于在数组中查找min元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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