其他分享
首页 > 其他分享> > 二分查找(BinarySort)

二分查找(BinarySort)

作者:互联网

 

/*
-------------------------------------------------
   Author:       wry
   date:         2022/3/2 11:20
   Description:  BinarySearch
-------------------------------------------------
*/

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1000+10;
int arr[MAXN];

bool BinarySearch(int left,int right,int p) {    //能否找到
    while (left<=right) {
        int middle = left + (right-left)/2;
        if (arr[middle]<p) {    //去右边找
            left = middle+1;
        }
        else if (arr[middle]>p) {
            right = middle-1;
        }
        else {
            return true;
        }
    }
    return false;
}

int main() {
    int n,p;
    while (cin >> n >> p) {
        for (int i=0;i<n;i++) {
            cin >> arr[i];
        }
        if (BinarySearch(0,n-1,p)) {
            cout << "Yes" << endl;
        }
        else {
            cout << "No" << endl;
        }
    }

    return 0;
}

 

标签:二分,arr,right,return,int,-------------------------------------------------,Binary
来源: https://www.cnblogs.com/wangry/p/15954648.html