Binary Search is a divide-and-conquer algorithm that searches for a target value in a sorted array by repeatedly dividing the search space in half. Unlike linear search which checks every element, binary search eliminates half of the remaining elements in each step.
Code:
int search(vector<int>& nums, int target) {
int s = 0;
int e = nums.size() - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (nums[mid] == target) {
return nums[mid];
} else if (target > nums[mid]) {
s = mid + 1;
} else {
e = mid - 1;
}
}
return -1;
}
Step 1: Understanding the problem size