0%

[題解]二分搜尋

a152. 二分搜尋

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define N 1005
#define FOR(i,n) for(int i=0;i<n;i++)
#define pii pair<int,int>
using namespace std;

int main(){
int n,arr[N];cin>>n;
for(int i=0;i<n;i++)cin>>arr[i];
int t;cin>>t;

int pos = 0,ans = 0,find = 0,l = 0,r = n-1; //[l,r]

while(l<=r){
int mid = (l+r)/2;
ans++;
if(arr[mid]==t){
pos = mid;find = 1;break;
}
else if(arr[mid]>t)r = mid-1;
else l = mid+1;
}
if(find)cout<<pos<<" "<<ans<<endl;
else cout<<"not found "<<ans<<endl;
}