7-18 maximum number in a unimodal array (15分)
You are a given a unimodal array of n distinct elements, meaning that its entries are in increasing order up until its maximum element, after which its elements are in decreasing order. Give an algorithm to compute the maximum element that runs in O(log n) time.
输入格式:
An integer n in the first line, 1<= n <= 10000. N integers in the seconde line seperated by a space, which is a unimodal array.
输出格式:
A integer which is the maximum integer in the array
输入样例:
7
1 2 3 9 8 6 5
输出样例:
9
#include<iostream>
using namespace std;
int main()
{
int n,a[10000],m;
int left = 0;
int right = n - 1;
cin >> n;
for(int i = 0;i < n;i++)
cin >> a[i];
m = (left + right) / 2;
while(left<=right)
{ m = (left + right) / 2;
if(m == 0 || m == n - 1) break;
if(a[m - 1] < a[m] && a[m + 1] < a[m])
{
cout << a[m];
return 0;
}
else if(a[m - 1] > a[m])
right = m - 1;
else if( a[m + 1] > a[m])
left = m + 1;
}
cout << a[m];
}