Write a function `binarySearch(arr, target)` that performs binary search on a sorted array and returns the index, or -1 if not found.
Problem Statement
Write a function `binarySearch(arr, target)` that performs binary search on a sorted array and returns the index, or -1 if not found.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Binary search works on sorted arrays by repeatedly halving the search range.
š” Hint 2:
Maintain left and right pointers. Check the middle element.
š” Hint 3:
If mid value < target, search right half. If mid value > target, search left half.
ā
Solution:
```javascript
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
```