二分查找(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;
}

 

上一篇:JS学习——数组排序


下一篇:输入输出,数据类型,数组,对象,函数