AI solution for JavaScript Coding Question on BFE.dev
37. implement Binary Search (unique)
function binarySearch(arr, num) {
let min = 0;
let max = arr.length - 1;
while (min <= max) {
let mid = Math.floor((min + max) / 2);
if (arr[mid] === num) {
return mid;
} else if (arr[mid] < num) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return -1;
}
Explanation:
The function takes in two arguments, an array and a number to be searched. First, we set min
to 0 and max
to the last index of the array. We then use a while loop to keep searching until min
is greater than max
. Inside the loop, we find the middle index of the array using (min + max) / 2
. If the middle value is equal to num
, we return the middle index. If the middle value is less than num
, we adjust min
to mid+1
so that we can eliminate the left half of the array from our search. If the middle value is greater than num
, we adjust max
to mid-1
so that we can eliminate the right half of the array. If we don't find the number, we return -1
.
Note: Since the array is unique and ascending, this implementation of binary search works efficiently with O(log n) time complexity.