Thuật toán tìm kiếm nhị phân C++
123456789101112131415161718192021222324252627//Thuat toan tim kiem nhi phan
#include<bits/stdc++.h>
using namespace std;
bool binary_search(int a[], int n, int x){
int l = 0, r = n-1, m;
while(l <= r){
m = (l + r) /2;
if(a[m] == x){
return true;
} else if(a[m] < x){
l = m +1;
} else r = m -1;
}
return false;
}
int main(){
int n, x; cin >> n >> x;
int a[n];
for(int &x : a) cin >> x;
sort(a, a + n);
if(binary_search(a, n, 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.