Binary Search
Medium
arrays
algorithms
Description
Implement the binary search algorithm to efficiently find a target value in a sorted array. Return the index of the target, or -1 if the target is not found.
Examples
Example1:
Input: array: [2, 5, 8, 12, 16], target: 12
Output: 3
Explanation: 12 is found at index 3.
Example2:
Input: array: [2, 5, 8, 12, 16], target: 7
Output: -1
Constraints
- Input array is sorted in ascending order.
- Output is an integer index (or -1).
- Must use an iterative or recursive binary search approach.
Loading...
Test Case 1
Input: [2,5,8,12,16],12
Output: 3
Test Case 2
Input: [2,5,8,12,16],7
Output: -1
Test Case 3
Input: [10,20,30,40],10
Output: 0
Test Case 4
Input: [10,20,30,40],40
Output: 3
