基本思想
- 给定数组,假设左边界为L,右边界为R
- 将数组分为两部分,[L] ~ [mid],[mid+1] ~ [R]
- 分别在两个部分上求最大值,然后比较这两部分的最大值
代码
public class ArrayMax {
public static void main(String[] args) {
int[] array = new int[]{1,2,3,5,9,5,6,8,12,45,656,65689,0,78};
int maxValue = getMaxValue(array,0,array.length-1);
System.out.println(maxValue);
}
private static int getMaxValue(int[] array, int L, int R) {
if (L == R){
return array[L];
}
int mid = L + ((R-L) >> 1);
int leftMaxValue = getMaxValue(array,L,mid);
int rightMaxValue = getMaxValue(array,mid+1,R);
return max(leftMaxValue,rightMaxValue);
}
private static int max(int leftMaxValue, int rightMaxValue) {
if (leftMaxValue >= rightMaxValue){
return leftMaxValue;
} else(leftMaxValue < rightMaxValue){
return rightMaxValue;
}
}
}
递归的实现过程
- 栈
- 程序递归过程中执行的信息会保存在栈内
- 记录执行信息后会销毁当前递归函数
- 递归到最内层,有返回值返回到栈顶,逐步重建函数,还原每次递归的现场
- 如果递归太多层,可能发生栈溢出(栈空间已满)
所有递归行为都可以改为非递归行为(迭代)
Master公式
- 某些递归行为的时间复杂度可以直接用公式算出
Master公式:T(N)=aT(N/b)+O(N^d)
- a、b、d都是常数
- 每个子问题的规模都是一致的 N/b
- 每次划分为 a个子问题(每次递归调用了a次)
- O(N^d)表示除递归外剩下所有过程的时间复杂度
- 符合公式时,计算时间复杂度
- log(b)(a) > d ===> O(N ^ log(b)(a))
- log(b)(a) < d ===> O(N ^ d)
- log(b)(a) = d ===> O(logN * N^d)
- 递归求数组最大值符合Master公式,T(N) = 2T(N/2) + O(N^0)