Find in half

The halved search is to compare the desired element with the middlemost element each time in the array arranged in ascending order. If it is larger than the middle, it is searched on the right;

#include<iostream>

using namespace std;
int num=0;
int find(int a[],int m,int left,int right)
{
while(left<=right)
{
num++;
int mid=(left+right)>>1;
if(m>a[mid])
left=mid+1;
else if(m<a[mid])
right=mid-1; else return mid; } return -1; } int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; int m; cin>>m; cout<<find(a,m,0,n-1)<<endl; cout<<num; return 0; }

















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324758426&siteId=291194637