算法初步P1.二分查找

算法初步P1.二分查找,第1张

算法初步P1.二分查找
#include 
#include 
#include 
using namespace std;
int n,m;
int find(int a[1000000],int num){
    int count = 0;
    int left = 0;
    int right = n - 1;
    while(true){
        if(a[left] == num){
            return left;
        }
        if(a[right] == num){
            return right;
        }
        if(a[(left+right)/2] > num){
            right = (left + right)/2;
        }
        if(a[(left+right)/2] < num){
            left = (left + right)/2;
        }
        if(a[(left+right)/2] == num){
            count = (left+right)/2;
            break;
        }
        if(left == right - 1||left == right){
            return -2;
        }
    }
    while((a[count - 1])==num){
        count--;
    }
    return count;
}
int main(){
    int a[1000000];
    int b[100000];
    cin >> n >> m;
    for(int i = 0;i < n;i++){
        cin >> a[i];
    }
    for(int i = 0;i < m;i++){
        cin >> b[i];
    }
    for(int i = 0;i < m;i++){
        cout << find(a,b[i])+1 << " ";
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3970369.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存