C++ STL Binary Search

  1. Understanding Binary Search
  2. Using std::binary_search in C++
  3. Custom Comparator for Binary Search
  4. Conclusion
  5. FAQ
C++ STL Binary Search

Binary search is a powerful algorithm that allows you to efficiently find an element in a sorted array. In C++, the Standard Template Library (STL) provides an easy-to-use implementation of binary search through the std::binary_search function.

This tutorial will walk you through the process of using the binary search algorithm in C++, showcasing its functionality and benefits. Whether you are a beginner looking to understand the basics or an experienced programmer wanting to refine your skills, this guide will provide valuable insights into the binary search method in C++. Let’s dive into the world of C++ STL and discover how to leverage binary search for efficient data retrieval.

Binary search operates on sorted arrays and utilizes a divide-and-conquer approach. The core idea is to repeatedly divide the search interval in half. If the target value is less than the middle element, the search continues in the lower half; otherwise, it proceeds to the upper half. This logarithmic time complexity makes binary search significantly faster than linear search, especially for large datasets.

To implement binary search in C++, you can use the std::binary_search function from the STL. This function checks whether a given element exists within a specified range of the sorted array. Let’s explore how to use this function effectively.

Using std::binary_search in C++

To use std::binary_search, you first need to include the necessary headers. Here’s a simple example:

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

int main() {
    std::vector<int> numbers = {1, 3, 5, 7, 9, 11};
    int target = 5;

    bool found = std::binary_search(numbers.begin(), numbers.end(), target);

    if (found) {
        std::cout << "Element found in the array." << std::endl;
    } else {
        std::cout << "Element not found in the array." << std::endl;
    }

    return 0;
}

Output:

Element found in the array.

In this code, we first include the necessary headers. We then create a vector of integers and define a target value to search for. The std::binary_search function takes the beginning and end iterators of the vector, along with the target value. If the target is found, it returns true; otherwise, it returns false. The result is printed to the console, indicating whether the element exists in the array.

Sometimes, you may want to perform a binary search using a custom comparison function. This is particularly useful when dealing with complex data types or specific sorting criteria. Here’s how to implement a binary search with a custom comparator:

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

struct Person {
    std::string name;
    int age;

    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};
    Person target = {"", 25};

    std::sort(people.begin(), people.end());

    bool found = std::binary_search(people.begin(), people.end(), target);

    if (found) {
        std::cout << "Person found in the array." << std::endl;
    } else {
        std::cout << "Person not found in the array." << std::endl;
    }

    return 0;
}

Output:

Person found in the array.

In this example, we define a Person struct with a name and age. We overload the < operator to compare Person objects based on age. After sorting the vector of Person objects, we perform a binary search using a target Person object. The search results are printed accordingly, showing whether the target person was found based on age.

Conclusion

In this tutorial, we’ve explored the binary search algorithm and its implementation through the C++ Standard Template Library. By utilizing std::binary_search, you can efficiently determine whether an element exists within a sorted array. We also discussed how to implement a custom comparator for more complex data types, enhancing the versatility of binary search. As you continue your programming journey, mastering binary search will undoubtedly improve your ability to handle data efficiently.

FAQ

  1. What is binary search?
    Binary search is an algorithm used to find the position of a target value within a sorted array by repeatedly dividing the search interval in half.

  2. How does std::binary_search work in C++?
    The std::binary_search function checks if a given element exists within a specified range of a sorted array, returning true if found and false otherwise.

  3. Can I use binary search on unsorted arrays?
    No, binary search only works on sorted arrays. You must sort the array first before using the binary search algorithm.

  4. What is the time complexity of binary search?
    The time complexity of binary search is O(log n), making it much more efficient than linear search for large datasets.

  5. Can I use binary search with custom data types?
    Yes, you can use binary search with custom data types by providing a custom comparator function to define the sorting criteria.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - C++ Algorithm