Binary Search
binary-search • array
Easy
Implement binary search to find a target in a sorted array.
Solution
Use two pointers (low, high) and repeatedly narrow the search window by comparing mid to target.
Return the index if found, otherwise -1.
Binary Search
binary-search • array
Easy
Implement binary search to find a target in a sorted array.
Solution
Use two pointers (low, high) and repeatedly narrow the search window by comparing mid to target.
Return the index if found, otherwise -1.
Code Solution
binary-search.cpp
cpp
1#include <vector>2using namespace std;34int binarySearch(const vector<int>& nums, int target) {5int lo = 0, hi = (int)nums.size() - 1;6while (lo <= hi) {7int mid = lo + (hi - lo) / 2;8if (nums[mid] == target) return mid;9if (nums[mid] < target) lo = mid + 1;10else hi = mid - 1;11}12return -1;13}