Problem:
Given an array, the value is incremented from small to large, and the maximum value is found by descending from the largest to the smallest.
Idea: The simplest way is to start with the second value and decide whether to meet A[i] > A[i-1] && a[i] > a[i+1]. If satisfied, I is the subscript for that maximum value. The complexity of the algorithm is O (n).
We can improve this algorithm, because this array is ordered, so we can use the idea of binary lookup, more quickly find the maximum value, time complexity of O (LG N).
Binary search algorithm can be found at the back of link, the exit condition of the binary search and the exit condition of the problem is not the same (see while loop), this is a very noteworthy place.
http://blog.csdn.net/beiyeqingteng/article/details/5736004
[Java]View PlainCopy
- public int Turningpoint (int[] A) {
- int m = a.length;
- int begin = 0;
- int end = M- 1;
- int TP = begin + (end-begin)/2;
- //The condition "TP > 0 && TP < m-1" makes sure that TP isn't at the beginning or the end
- While (TP > 0 && TP < m-1) {
- if (A[TP] > A[TP + 1] && A[TP] > A[TP-1]) {
- return TP;
- } Else if (A[TP] < a[tp+1]) {
- BEGIN = TP + 1;
- TP = begin + (end-begin)/2;
- } Else {
- END = TP- 1;
- TP = begin + (end-begin)/2;
- }
- }
- return-1;
- }
Ordered array Ordering