Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Binary Search in C++ with Lower Bound

Tech May 1 25

Binary search is an efficient algorithm for locating a target value within a sorted sequence. The standard implementation returns the position of any matching element, but may not identify the first occurence when duplicates exist.

int binarySearch(int left, int right, int target) {
    int result = -1;
    while (left <= right) {
        int middle = left + (right - left) / 2;
        if (data[middle] == target) {
            result = middle;
            right = middle - 1; // Continue searching left for first occurrence
        } else if (data[middle] < target) {
            left = middle + 1;
        } else {
            right = middle - 1;
        }
    }
    return result;
}

This modified version continues searching leftward after finding a match to ensure the first occurrence is returned.

C++ provides built-in functions for binary search operations through the <algorithm> header. The lower_bound function returns an iterator to the first element that is not less than the target value.

#include <algorithm>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {1, 3, 3, 3, 5, 7, 9, 11, 13, 15, 15};
    int target = 3;
    
    auto position = lower_bound(numbers.begin(), numbers.end(), target);
    int index = position - numbers.begin();
    
    if (position != numbers.end() && *position == target) {
        cout << "First occurrence at index: " << index << endl;
    } else {
        cout << "Target not found" << endl;
    }
    
    return 0;
}

When the target value exists in the collection, lower_bound returns an iterater to the first occurrence. If the target is not found, it returns an iterator to the first element greater than the target, or end() if no such element exists.

The upper_bound function complements lower_bound by returning an iterator to the first element strictly greater than the target value. Together, these functions can idenitfy all occurrences of a value in a sorted range.

vector<int> data = {2, 4, 4, 4, 6, 8};
int value = 4;

auto lower = lower_bound(data.begin(), data.end(), value);
auto upper = upper_bound(data.begin(), data.end(), value);

// The range [lower, upper) contains all occurrences of value
int count = upper - lower; // Returns 3 for this example

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.