分治法求数组的最小值和最大值

**
 * 
 * 分治法求数组的最小值和最大值
 */
import java.util.Arrays;

public class MinAndMaxArray {
	public static void main(String[] args) {
		int arr[] = { -2, -9, 0, 5, 2 };
		int result[] = new int[2];
		result = minMax(arr, 0, arr.length - 1);
		System.out.println(Arrays.toString(result));
	}

	public static int[] minMax(int[] arr, int l, int r) {
		int min = 0;
		int max = 0;
		if (l == r) {
			min = arr[l];
			max = arr[l];
		} else if (l + 1 == r) {
			if (arr[l] < arr[r]) {
				min = arr[l];
				max = arr[r];
			} else {
				min = arr[r];
				max = arr[l];
			}
		} else {
			int mid = (l + r) / 2;
			int[] preHalf = minMax(arr, l, mid);
			int[] postHalf = minMax(arr, mid + 1, r);
			min = preHalf[0] < postHalf[0] ? preHalf[0] : postHalf[0];
			max = preHalf[1] > postHalf[1] ? preHalf[1] : postHalf[1];
		}

		return new int[] { min, max };
	}
}


运行结果:

[-9, 5]


你可能感兴趣的:(分治法求数组的最小值和最大值)