Problem
We are required to write a JavaScript function that takes in a sorted array of numbers (increasing order), arr, as the first argument, and a target number as the second argument. Our function should search target in array arr using the binary search algorithm since the array is sorted.
If the target exists, then we should return its index, otherwise we should return -1.
For example, if the input to the function is
Input
const arr = [3, 5, 7, 9, 11, 13, 15, 16, 18, 21, 24, 25, 28]; const target = 13;
Output
const output = 5;
Example
Following is the code −
const arr = [3, 5, 7, 9, 11, 13, 15, 16, 18, 21, 24, 25, 28]; const target = 13; const binarySearch = (arr = [], target) => { const helper = (low, high) => { if (low > high) { return -1 } const middle = Math.floor((low + high) / 2) if (arr[middle] === target) { return middle } if (arr[middle] < target) { return helper(middle + 1, high) } return helper(low, middle - 1) } return helper(0, arr.length - 1) }; console.log(binarySearch(arr, target));
Output
5