How do I binary search with algorithms with std::stack?

Binary searching is an efficient algorithm for finding a target value within a sorted array or list. In C++, the standard library provides various utilities, but using `std::stack` directly for binary search is unconventional. However, you can emulate a binary search approach using a stack to manage the search range iteratively. Here’s how you can achieve this.

C++, binary search, std::stack, algorithms, search algorithms, iterative approach
This example demonstrates how to implement a binary search algorithm using std::stack in C++. It provides an iterative approach to searching for a target value in a sorted array.

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int binarySearchWithStack(const vector& arr, int target) {
    stack> s; // Stack to hold the left and right bounds
    s.push({0, static_cast(arr.size()) - 1});
    
    while (!s.empty()) {
        auto [left, right] = s.top();
        s.pop();
        
        if (left > right) continue; // Skip if bounds are invalid
        
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == target) {
            return mid; // Found the target
        } else if (arr[mid] < target) {
            s.push({mid + 1, right}); // Search in the right half
        } else {
            s.push({left, mid - 1}); // Search in the left half
        }
    }
    
    return -1; // Target not found
}

int main() {
    vector sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int target = 4;
    int index = binarySearchWithStack(sortedArray, target);
    
    if (index != -1) {
        cout << "Element found at index: " << index << endl;
    } else {
        cout << "Element not found!" << endl;
    }
    
    return 0;
}
    

C++ binary search std::stack algorithms search algorithms iterative approach