Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 크루스칼
- lis
- 문자열
- 스택
- MST
- 링크드리스트
- BeautifulSoup
- 큐
- BFS
- SSAFY
- dfs
- 중복 순열
- Knapsack
- 이분 탐색
- 백트래킹
- 분할 정복
- 우선순위 큐
- 조합
- 빠른 입출력
- 완전 탐색
- 재귀
- 피보나치 수
- 메모리풀
- 그리디
- 시뮬레이션
- 순열
- 클래스
- 세그먼트 트리
- 비트마스크
- DP
Archives
- Today
- Total
작심 24/7
이진 탐색 (Binary Search) 본문
#include <iostream>
using namespace std;
int arr[8] = {1, 2, 4, 5, 10, 21, 21, 22};
int binarySearch(int st, int en, int target) { // target 찾음
while (st <= en) {
int mid = (st + en) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) st = mid + 1;
else en = mid - 1;
}
return -1;
}
int upperBound(int st, int en, int target){ // target보다 큰 첫 번째 수 찾음
int res = -1;
while (st <= en) {
int mid = (st + en) / 2;
if (arr[mid] > target){
res = mid;
en = mid - 1;
}
else st = mid + 1;
}
return res;
}
int lowerBound(int st, int en, int target){ // target보다 크거나 같은 첫 번째 수 찾음
int res = -1;
while (st <= en) {
int mid = (st + en) / 2;
if(arr[mid] >= target){
res = mid;
en = mid - 1;
}
else st = mid + 1;
}
return res;
}
int main(){
cout << binarySearch(0, 7, 21) << "\n";
cout << upperBound(0, 7, 21) << "\n";
cout << lowerBound(0, 7, 21) << "\n";
return 0;
}
'개념' 카테고리의 다른 글
힙 (Heap) (0) | 2022.02.14 |
---|---|
비트마스크 (BitMask) (0) | 2021.08.07 |
7. 계수 정렬 (Counting Sort) (2) | 2020.05.22 |
6. 힙 정렬 (Heap Sort) (0) | 2020.05.22 |
5. 합병 정렬 (Merge Sort) (0) | 2020.05.20 |
Comments