#include <algorithm>
직접 이분탐색을 짰을 때 무한 루프에 빠지는 게 걱정되면 st와 en이 1 차이날 때를 주의 깊게 확인하자.
bool binarySearch(int target) { // 💥 탐색 대상이 되는 배열이 이미 오름차순으로 정렬되어 있어야 함.
int st = 0, en = N - 1;
while (st <= en) {
int mid = (st + en + 1) / 2;
if (A[mid] < target) st = mid + 1;
else if (A[mid] > target) en = mid - 1;
else return true; // 탐색 성공! 이럼 target과 같은 값을 찾은거니까
}
return false; // 탐색 실패! st > en일 경우 while문을 탈출
}
binary_search())binary_search 함수가 있어서 범위를 주면 주어진 범위 내에 원소가 들어있는지 여부를 에 true 혹은 false로 알려준다.int a[100005];
int n;
int main(void) {
cin >> n;
for(int i = 0; i < n; i++) cin >> a[i];
sort(a, a+n);
int m;
cin >> m;
while(m--) {
int t;
cin >> t;
cout << binary_search(a, a+n, t) << '\n';
}
}
❗
vector에서 탐색을 할 경우v.begin(),v.end()를 인자로 넘겨주면 된다.
lower_bound는 찾으려는 key 값보다 같거나 큰 숫자가 배열 몇 번째에서 처음 등장하는지 찾아줌upper_bound는 찾으려는 key 값을 초과하는 숫자가 배열 몇 번째에서 처음 등장하는지 찾아줌equal_range는 (lower_bound, upper_bound)의 쌍(std::pair 객체)을 리턴함lower_bound(arr, arr + 6, 6) - arr; 이런 식으로 사용arr + 6)upper_bound에서 lower_bound를 빼는 아이디어가 유효하다.sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
lower_bound() 함수로 해당 원소의 인덱스를 찾는다.int index = lower_bound(v.begin(), v.end(), num) - v.begin();