【二分查找】无重复数组的二分查找(非递归版本)

// 二分查找法
#include <iostream>
#include <vector>
using namespace std;
int BinarySearch(vector<int> vec,int target)
{
    // 特殊输入
    if(vec.size() <= 0)
        return -1;

    // 二分查找(非递归)
    int low = 0;
    int mid = 0;
    int high = vec.size()-1;

    // 注意:取等号
    while(low <= high)
    {
        mid = (low + high)/2;

        if(vec[mid] == target)
            return mid;

        if(vec[mid] > target)
            high = mid-1;
        else
            low = mid+1;

    }
    return -1;
}

int main()
{
    vector<int> vec = {1,2,3,5,7,7,7,7,9,10};
    int target;
    while(cin>>target)
        cout<<BinarySearch(vec,target)<<endl;
    return 0;
}
posted @ 2018-07-29 10:18  wanglei5205  阅读(379)  评论(0编辑  收藏  举报
levels of contents