이진 검색은 정렬된 배열 내에서 대상 값의 위치를 찾는 검색 알고리즘입니다. 이진 검색은 대상 값을 정렬된 배열의 중간 요소와 비교합니다. 이진 탐색의 시간 복잡도는 O(1)입니다. 여러가지를 구현한 C++ 프로그램입니다. C++ STL의 이진 검색 기능
알고리즘
Begin Initialize the vector of integer values. The functions are used here: binary_search(start_pointer, end_pointer, value) = Returns true if the value present in array otherwise false. lower_bound(start_pointer, end_pointer, value) = Returns pointer to “position of value” if container contains 1 occurrence of value. Returns pointer to “first position of value” if container contains multiple occurrence of value. Returns pointer to “position of next higher number than value” if container does not contain occurrence of value. upper_bound(start_pointer, end_pointer, value) = Returns pointer to “position of next higher valuethan value” if container contains 1 occurrence of value. Returns pointer to “first position of next higher number than last occurrence of value” if container contains multiple occurrence of value. Returns pointer to “position of next higher number than value” if container does not contain occurrence of value. Print the results. End.
예시 코드
#include<bits/stdc++.h> using namespace std; int main() { vector<int> a = {6,7,10,14,16,20}; if (binary_search(a.begin(), a.end(), 50)) cout << "50 exists in vector"; else cout << "50 does not exist"; cout << endl; if (binary_search(a.begin(), a.end(), 7)) cout << "7 exists in the vector"; else cout << "7 does not exist"; cout << endl; cout << "The position of 7 using lower_bound "; cout << lower_bound(a.begin(), a.end(), 7) - a.begin(); cout << endl; cout << "The position of 7 using upper_bound "; cout << upper_bound(a.begin(), a.end(), 7) - a.begin(); cout << endl; }
출력
50 does not exist 7 exists in the vector The position of 7 using lower_bound 1 The position of 7 using upper_bound 2