在Java中,如何搜尋陣列中的最小值和最大元素?
此範例顯示如何使用Collection
類的Collection.max()
和Collection.min()
方法來搜尋陣列中的最小和最大元素。
package com.yiibai;
import java.util.Arrays;
import java.util.Collections;
public class ArraySearchMaxMin {
public static void main(String[] args) {
int numbers[] = new int[] { 28, 21, 17, 41, 34, 29, 15 };
int s = numbers[0];
int l = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > l)
l = numbers[i];
else if (numbers[i] < s)
s = numbers[i];
}
System.out.println("Largest Number is : " + l);
System.out.println("Smallest Number is : " + s);
}
}
執行上面範例程式碼,得到以下結果 -
Largest Number is : 41
Smallest Number is : 15
範例2
陣列中最小和最大元素的另一個範例範例。
package com.yiibai;
import java.util.Arrays;
import java.util.Collections;
public class ArraySearchMaxMin2 {
public static void main(String[] args) {
Integer[] numbers = { 18, 22, 7, 15, 40, 19, 25 };
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("Min number: " + min);
System.out.println("Max number: " + max);
}
}
執行上面範例程式碼,得到以下結果 -
Largest Number is : 40
Smallest Number is : 7