Algorithms fourth edition at http://algs4.cs.princeton.edu/14analysis/
Chapter 1. 1.4 Analysis of Algorithms
Creative Problems 18
- Local minimum of an array. Write a program that, given an array a[] of N distinct integers, finds a local minimum: an index i such that botha[i] < a[i-1] and a[i] < a[i+1] (assuming the neighboring entry is in bounds). Your program should use ~2 lg N compares in the worst case.
Answer: Examine the middle value a[N/2] and its two neighbors a[N/2 - 1] and a[N/2 + 1]. If a[N/2] is a local minimum, stop; otherwise search in the half with the smaller neighbor.
三种情况:
Case 1:当a[N/2 - 1] < a[N/2],假设满足0<i<N/2的a[i]中不存在local minimum, 则a[N/2 - 2] < a[N/2 - 1].依次类推最后得a[0]<a[1].但此时a[0]为local minimum。
所以0<i<N/2时必然存在local minimum。
Case 2:当a[N/2 + 1] <a[N/2]时,与Case 1类似。
Case 3:当a[N/2 - 1] > a[N/2]且a[N/2 + 1] > a[N/2]时a[N/2]为local minimum
Notes:
从NxN的2维数组寻找local minimum的时候也可以采取类似的方法。满足O(n)
http://stackoverflow.com/questions/18525179/find-local-minimum-in-n-x-n-matrix-in-on-time
从N/2列和N/2行选择最小的元素,依次类推到找到local minimum为止
local minimum的范围不会超过N/2xN/2,因为N/2xN/2内的值比N/2行与N/2列的最小值还小
所以worst case下找到local minimum需要 2N + 2N/2 + 2N/4 + ... =