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.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?