數組中查找最大值和最小值 (兩種方法)


//獲取數組中元素的最大值,方法一
public static int getMax(int[] arr){
int max = arr[0];

for(int x=1; x<arr.length; x++){
if(arr[x]>max){
max = arr[x];

}
return max;

}
//獲取數組元素中的最大值,方法二
public static int getMax_2(int[] arr){
int max = 0;

for(int x=1; x<arr.length; x++){
if(arr[x]>arr[max]){
max = x;

}
return max;

}

//獲取數組元素中的最小值。
public static int getMin(int[] arr){
int min=arr[0];
for(int x = 1;x<arr.length;x++){

if(min>arr[x]){
min=arr[x];
}
}
return min;

}
//方法重載,具有相同的功能,不同的函數名。
public static double getMax(double[] arr){
return 0;

}


//求最小值的輸出語句
public static void main(String[] args) {
int[] arr={4,5,2,6,8,3,7,3};
int max = getMax(arr);
int min = getMin(arr);
System.out.println(max);
System.out.println(min);
boolean[] ar = new boolean[4];
System.out.println(ar[2]);
}
}
//此處為求最大值的輸出語句。
/*
public static void main(String[] args) {
int[] arr = {1,4,6,3,7,3,9,2};
int max = getMax_2(arr);
//System.out.println(max);
System.out.println(arr[max]);
}
}

    1. */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM