#include <iostream>
#include <algorithm> // sort함수
int arr[1000];
int n;
int binarySearch(int target) {
int start = 0;
int end = n - 1;
while (start <= end) {
int mid = (start + end) / 2; // c++은 기본적으로 소수점 버림함
// 오버플로우 방지를 위해 아래와 같이 쓸 수 있다.
// mid = start + (end - start) / 2
if (arr[mid] < target)
start = mid + 1;
else if (arr[mid] > target)
end = mid - 1;
else
return 1;
}
return 0; // 찾는 수가 없으면 start > end가 되므로 while문 탈출
}
int main()
{
std::ios::sync_with_stdio(0);
std::cin.tie(0);
std::cin >> n;
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
std::sort(arr, arr + n);
int t = 0;
std::cin >> t;
binarySearch(t);
}
< 참고자료 >
https://blog.encrypted.gg/985
[실전 알고리즘] 0x13강 - 이분탐색
안녕하세요, 이번 시간에는 이분탐색을 배워보도록 하겠습니다. 사실 이분탐색의 개념 자체는 그렇게 어렵지는 않습니다. 초등학생 정도만 되어도 업다운게임같은걸 아주 재밌게 즐길 수 있고,
blog.encrypted.gg
'CS > C++' 카테고리의 다른 글
| C++로 BFS, DFS 구현 (0) | 2023.08.09 |
|---|---|
| C++ 정수, 실수 자료형 범위와 주의할 점 (0) | 2023.07.21 |
| [C++] Vector VS List (0) | 2023.07.20 |
| C++ Deque VS Vector (0) | 2023.07.12 |
| C++로 덱 구현 (0) | 2023.07.11 |