三種方式查找數組中最大值和最小值數組
第三種我的以爲很好。spa
public class ArrayAlg { public static void main(String[] args) { //找數組中的最大值 double[] doubles={22.1,32.5,56.2,45.2,78.2}; /* 方法一:Arrays.sort(doubles); System.out.println(Arrays.toString(doubles)); System.out.println("最大值爲:"+doubles[doubles.length-1]); System.out.println("最小值爲:"+doubles[0]); */ /*方法二:double max=doubles[0]; for (int i=0;i<doubles.length-1;i++){ if (max<doubles[i+1]){ max=doubles[i+1]; } } System.out.println("最大值爲:"+max); double min=doubles[0]; for (int i=0;i<doubles.length-1;i++){ if (min>doubles[i+1]){ min=doubles[i+1]; } } System.out.println("最小值爲:"+min); */ /*方法三:double min=Double.POSITIVE_INFINITY; double max=Double.NEGATIVE_INFINITY; for (double d:doubles){ if (min>d){ min=d; } if (max<d){ max=d; } } System.out.println("最大值爲:"+max+"最小值"+min); */
//冒泡排序
for (int i=0;i<doubles.length-1;i++){
for (int j=0;j<doubles.length-1-i;j++){
if (doubles[j]>doubles[j+1]){
double temp=doubles[j+1];
doubles[j+1]=doubles[j];
doubles[j]=temp;
}
}
}
System.out.println(Arrays.toString(doubles));
}
} }