Binary Search
JAVASCRIPT
Hard
+50 XP
Problem Description
Write a function `binarySearch(arr, target)` that searches a sorted array for `target` and returns its index, or -1 if not found.
You must use the binary search algorithm (O(log n)), not linear search.
Example:
binarySearch([1,3,5,7,9], 5) → 2
binarySearch([1,3,5,7,9], 4) → -1
binarySearch([2,4,6,8,10], 10) → 4
You must use the binary search algorithm (O(log n)), not linear search.
Example:
binarySearch([1,3,5,7,9], 5) → 2
binarySearch([1,3,5,7,9], 4) → -1
binarySearch([2,4,6,8,10], 10) → 4
Test Cases
Input: binarySearch([1,3,5,7,9], 5)
Expected: 2
Input: binarySearch([1,3,5,7,9], 4)
Expected: -1
Input: binarySearch([2,4,6,8,10], 10)
Expected: 4
Input: binarySearch([], 1)
Expected: -1
Your Solution