1. 程式人生 > >遞迴(簡單的例子)

遞迴(簡單的例子)

eg:在一個數組中,先找到左半部分的最大值,再找到右半部分的最大值。

package basic_class_01;

public class Code_04_diGui {

	public static int getMax(int[] arr, int L, int R) {
		if (L == R) {
			return arr[L];
		}

		int mid = (L + R) / 2;

		int maxLeft = getMax(arr, L, mid);
		int maxRight = getMax(arr, mid + 1, R);
		return Math.max(maxLeft, maxRight);
	}

	public static void main(String[] args) {
		int[] a = { 4, 3, 2, 1 };
		System.out.println(getMax(a, 0, a.length - 1));
	}
}

分析: