给定一个含有n个元素的整型数组a,求a中的最大值和最小值。用递归实现。
public class MaxAnsMinInArr { public static void main(String[] args) { // TODO 自动生成的方法存根 int[] arr = new int[2]; int[] a = {1,8,1,84,4,9,102,74,52,3,30,55,84}; int l = 0,r=a.length-1; maxAndMinArr(a, l, r, arr); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } private static void maxAndMinArr(int[] a, int l, int r, int[] ret){ if (l == r) { ret[0] = a[l]; ret[1] = a[l]; return; } if (l + 1 ==r) { if (a[l] >= a[r]) { ret[0] = a[r]; ret[1] = a[l]; } else { ret[0] = a[l]; ret[1] = a[r]; } return; } int m = (l + r) / 2; int[] larr = new int[2]; maxAndMinArr(a, l, m, larr); int[] rarr = new int[2]; maxAndMinArr(a, m+1, r, rarr); ret[0] = min(larr[0],rarr[0]); ret[1] = max(larr[1],rarr[1]); } public static int min(int lmin,int rmin){ return lmin < rmin ? lmin : rmin; } public static int max(int lmax,int rmax){ return lmax > rmax ? lmax : rmax; } }