求一个数组中的最大值和最小值,两种方式:
public class MaxDemo {
public static void main(String[] args) {
int [] num ={123,43,435,46,57,68,78,7,98};
int max = Max(num);
int min = Min(num);
System.out.println("最大数值是"+max);
System.out.println("最大数值是"+min);
Max_Min(num);
}
//求最大数
public static int Max(int []num){
int max = num[0];
int length = num.length;
for(int i = 1; i < length;i++){
if(max < num[i]){
num[i] = num[i]+max;
max = num[i]- max;
num[i] = num[i]- max;
}
}
return max;
}
//求最小值
public static int Min(int [] num){
int min = num[0];
int length = num.length;
for(int i = 1; i < length;i++){
if(min > num[i]){
num[i] = num[i]+min;
min = num[i]-min;
num[i] = num[i]-min;
}
}
return min;
}
public static void Max_Min(int []num ){
int min = num[0],max = num[0];
int length = num.length;
for(int i = 0; i < length;i++){
if(max > num[i]){
max=num[i];
}
if(min < num[i]){
min=num[i];
}
}
System.out.println("最大数值是"+max);
System.out.println("最大数值是"+min);
}
}
个人跟喜欢第二种方式,简洁。