二分查找

//说明
//输入已经按升序排好的数组num,需要查找的元素X
//输出X在num中的索引,如果不存在,输出-1
//采用二分查找,时间复杂度O(logN)
#include<iostream>
#include<vector>
using namespace std;
void main()
{
    cout<<"Input:"<<endl;
    int a;
    char b;
    int N=0;
    int temp;
    vector<int> num;
    while(cin>>a)
    {
        b=cin.get();
        num.push_back(a);
        if(b=='
')
            break;

    }
    N=num.size();
    cout<<"The number you want to find:"<<endl;
    int X;
    cin>>X;
    //二分查找
    int index;
    int low=0;
    int high=N-1;

    while(high>=low)
    {
        int mid=(low+high)/2;
        if(num[mid]==X)
        {
            index=mid;
            break;
        }
        else if(num[mid]<X)
        {
            low=mid+1;
        }
        else
            high=mid-1;
    }
    if(high<low)
        index=-1;
    cout<<"the index of X in vector num is:"<<index<<endl;
}
原文地址:https://www.cnblogs.com/riden/p/4564414.html