java 获取数组最值的三种方法

发布于:2021-10-16 20:23:15

//数组获取最大值和最小值
public static void mxi(){
//第一种,用集合操作类max,min
Integer[] nums = {8, 2, 7, 1, 4, 9, 5};
int min = (int)Collections.min(Arrays.asList(nums));
int max = Collections.max(Arrays.asList(nums));
System.out.println("最小值:"+min);
System.out.println("最大值:"+max);

//第二种,数组操作类sort排序
Integer[] nums1 = {8, 2, 7, 1, 4, 9, 5};
Arrays.sort(nums1);
System.out.println("最小值:"+nums1[0]);
System.out.println("最大值:"+nums1[nums1.length-1]);

//第三种,冒泡去最值
int t;
Integer[] nums2 = {8, 2, 7, 1, 4, 9, 5};
for (int i = 1; i
for (int j = 0; j < nums2.length-i; j++) {
if(nums2[j] > nums2[j+1]){
t = nums2[j];
nums2[j] = nums2[j+1];
nums2[j+1] = t;
}
}
}
System.out.println("最小值:"+nums2[0]);
System.out.println("最大值:"+nums2[nums2.length-1]);

}

相关推荐

最新更新

猜你喜欢