算法题:二分查找的溢出考虑

#include <iostream>
using namespace std;

int find_val(int a[],int n,int val)
{
    int low = 0;
    int high = n-1;
    while(low<=high)
    {
        //mid=(high+low)/2;//可能溢出。
        int mid = low+(high-low)/2;
        if(a[mid]>val)
            {
                high = mid-1;
            }
        else if(a[mid]<val)
            {   
                low = mid+1;
            }
        else
            {
                return a[mid];
            }
    }
    return -1;
}
int main()
{
    int a[]={1,2,3,4,5,6,7,8,9};
    cout<<find_val(a,sizeof(a)/sizeof(int),6)<<endl;;
    return 0;
}
    原文作者:查找算法
    原文地址: https://blog.csdn.net/liuhuiyan_2014/article/details/48041241
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞