Thuật toán tìm kiếm nhị phân
1234567891011121314151617181920212223//Thuat toan tim kiem nhi phan bang de quy
#include<bits/stdc++.h>
using namespace std;
bool binary_search(int a[], int l, int r, int x){
if(l > r) return false;
int m = (l + r)/2;
if(a[m] == x) return true;
else if(a[m] < x){
return binary_search(a, m+1, r, x);
}
else return binary_search(a, l, m-1, x);
}
int main(){
int n, x; cin >> n >> x;
int a[n];
for(int &x : a) cin >> x;
if(binary_search(a, 0, n-1, x)){
cout << "Found" << endl;
} else cout << "Not Found" << endl;
return 0;
}
Đăng nhận xét
Click to see the code!
To insert emoticon you must added at least one space before the code.