💡 퀵 접속: cpp.kr/binary_search

binary_search

C++ 표준 라이브러리의 알고리즘으로, 정렬된 범위에서 이진 탐색을 수행하여 특정 값을 찾습니다. 값이 존재하면 true를, 존재하지 않으면 false를 반환합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 7이 존재하는지 확인
    bool found = std::binary_search(v.begin(), v.end(), 7);
    
    std::cout << "7이 존재하는가? " << (found ? "예" : "아니오") << std::endl;
    
    // 11이 존재하는지 확인
    found = std::binary_search(v.begin(), v.end(), 11);
    
    std::cout << "11이 존재하는가? " << (found ? "예" : "아니오") << std::endl;
    
    return 0;
}

실행 결과:

7이 존재하는가? 예
11이 존재하는가? 아니오

커스텀 비교 함수 사용

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    
    // 내림차순 정렬된 벡터에서 7 찾기
    bool found = std::binary_search(v.begin(), v.end(), 7,
                                  std::greater<int>());
    
    std::cout << "7이 존재하는가? " << (found ? "예" : "아니오") << std::endl;
    
    return 0;
}

실행 결과:

7이 존재하는가? 예

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
    std::string name;
    int age;
    
    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35}
    };
    
    // 30세인 사람 찾기
    Person target{"", 30};
    bool found = std::binary_search(people.begin(), people.end(), target);
    
    std::cout << "30세인 사람이 존재하는가? " << (found ? "예" : "아니오") << std::endl;
    
    return 0;
}

실행 결과:

30세인 사람이 존재하는가? 예

참고사항

  • binary_search는 algorithm 헤더에 정의되어 있습니다.
  • 탐색하려는 범위는 반드시 정렬되어 있어야 합니다.
  • 기본적으로 < 연산자를 사용하여 비교합니다.
  • 커스텀 비교 함수를 제공할 수 있습니다.
  • 시간 복잡도는 O(log n)입니다.
함수 설명
binary_search(first, last, value) 기본 비교 연산자를 사용하여 이진 탐색
binary_search(first, last, value, comp) 커스텀 비교 함수를 사용하여 이진 탐색