7-17 maximum number in a unimodal array (25 分)

7-17 maximum number in a unimodal array (25 分)
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
结尾无空行
解析:使用二分搜素找最大值,先找出中间的数 i 和 i-1 进行比较,有两种情况。1.若 i 小于 i-1 则从 i 的左边继续进行比较;
2.若 i 大于 i-1 则从 i 的右边继续进行比较;

#include <iostream>
using namespace std;
int BinarySearch(int a[], int m, int n);
int main()
{
    int n,m=0;
    cin>>n;
    int a[10010];
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    int x=BinarySearch(a,m,n);
   cout << x;
   return 0;
}
int BinarySearch(int a[],int m,  int n)
{
    int middle=n/2;
    while(a[middle]>a[middle-1]&&middle<=n)
    {
        middle++;
    }
    m=a[middle-1];
    return m;
    while(a[middle]<a[middle-1]&&middle>1)
    {
        middle--;
    }
    m=a[middle-1];
    return m;
}

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值