Binary Search

From Wiki
Jump to navigation Jump to search

Binary Search[edit]

Binary Search is an efficient algorithm for finding a specific element (target) in a sorted array or list. The algorithm works by repeatedly dividing the search interval in half. At each step, the algorithm compares the middle element of the interval with the target value. If the middle element is equal to the target, the search is successful. If the target is less than the middle element, the search continues in the left half of the interval. If the target is greater than the middle element, the search continues in the right half of the interval.

Time Complexity[edit]

The time complexity of binary search is O(log N), where N is the number of elements in the sorted array or list.

C++ Code Example[edit]


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

using namespace std;

// Function to find a target element in a sorted vector
int binary_search_any(const vector<int>& nums, int target) {
    int low = 0, high = nums.size() - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return -1; // Target not found
}

// Function to find the lowest index of the target element in a sorted vector
int binary_search_lowest(const vector<int>& nums, int target) {
    int low = 0, high = nums.size() - 1;
    int ans = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (nums[mid] == target) {
            ans = mid;
            high = mid - 1;
        } else if (nums[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return ans;
}

// Function to find the highest index of the target element in a sorted vector
int binary_search_highest(const vector<int>& nums, int target) {
    int low = 0, high = nums.size() - 1;
    int ans = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (nums[mid] == target) {
            ans = mid;
            low = mid + 1;
        } else if (nums[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return ans;
}

int main() {
    vector<int> nums = {1, 2, 2, 2, 3, 4, 5};

    int target = 2;
    int anyIndex = binary_search_any(nums, target);
    int lowestIndex = binary_search_lowest(nums, target);
    int highestIndex = binary_search_highest(nums, target);

    cout << "Any index of target " << target << ": " << anyIndex << endl;
    cout << "Lowest index of target " << target << ": " << lowestIndex << endl;
    cout << "Highest index of target " << target << ": " << highestIndex << endl;

    return 0;
}


C++ Built-in Binary Search[edit]

C++ provides built-in binary search algorithms in the Standard Template Library (STL) that can be used when direct implementation of the binary search algorithm is not necessary. The <algorithm> header provides three main binary search functions: lower_bound, upper_bound, and binary_search.

lower_bound[edit]

The lower_bound function returns an iterator pointing to the first element in the range that is not less than the given value. If the element is not found, it returns an iterator pointing to the first element greater than the given value.

upper_bound[edit]

The upper_bound function returns an iterator pointing to the first element in the range that is greater than the given value.

binary_search[edit]

The binary_search function returns a boolean indicating whether the given value is present in the range or not. It does not return the position of the element.

Here's an example of using the built-in C++ binary search functions:


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

using namespace std;

int main() {
    vector<int> nums = {1, 2, 2, 2, 3, 4, 5};

    int target = 2;
    // Using lower_bound to find the first occurrence of the target
    auto lb = lower_bound(nums.begin(), nums.end(), target);
    if (lb != nums.end() && *lb == target) {
        cout << "First occurrence of target " << target << " is at index: " << lb - nums.begin() << endl;
    } else {
        cout << "Target " << target << " not found" << endl;
    }

    // Using upper_bound to find the position just after the last occurrence of the target
    auto ub = upper_bound(nums.begin(), nums.end(), target);
    cout << "Position after last occurrence of target " << target << " is at index: " << ub - nums.begin() << endl;

    // Using binary_search to check if the target is present in the range
    bool isPresent = binary_search(nums.begin(), nums.end(), target);
    cout << "Target " << target << (isPresent ? " is present" : " is not present") << " in the range" << endl;

    return 0;
}