在数组中查找min元素

在数组中查找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.)