• 二分查找


    //说明
    //输入已经按升序排好的数组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;
    }
  • 相关阅读:
    P1541 乌龟棋 暴力DP
    HDU
    HDU-6608 Fansblog 数论 ,威尔逊定理,快速乘
    P3842 [TJOI2007]线段 思维 ,DP
    模板 BSGS
    Gym
    HDU
    HDU
    HDU
    P1095 守望者的逃离 暴力DP
  • 原文地址:https://www.cnblogs.com/riden/p/4564414.html
Copyright © 2020-2023  润新知