public class Test { public static void main(String[] args) { int[] array = {12,34,5,6,89,2,345}; System.out.println(getMax(array)); System.out.println(getMax2(array)); } public static int getMax(int[] arr) { int max = arr[0]; for(int x = 1;x < arr.length;x++) { if(max < arr[x]) { max = arr[x]; } } return max; } public static int getMax2(int[] arr) { int maxIndex = 0; for(int x = 1;x<arr.length;x++) { if(arr[maxIndex]<arr[x]) { maxIndex = x; } } return arr[maxIndex]; } }
求最大值就是不断两两比较取较大值。
第一种方法:
是将数组第一个值先作为最大值,然后通过for循环遍历其他元素,如果遍历到的元素比当前最大值max的值大,那就通过赋值给max而达到max的值始终是最大值。遍历结束后,max即为当前最大值。
第二种方法:
是比较下标,如果下标所在的元素的值在比较中是较大的,则保存下标到maxIndex上,而不断比较使得maxIndex所在元素始终是最大的。
最小值同理
代码:
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 int getMin2(int[] arr) { int minIndex = 0; for(int x = 1;x<arr.length;x++) { if(arr[minIndex]>arr[x]) { minIndex = x; } } return arr[minIndex]; }