We are required to write a JavaScript function that takes in a sorted array of numbers as the first argument and a search number as the second argument.
If the search number exists in the array, we need to return its index in the array, otherwise we need to return -1.
We have to do this making use of the binary search algorithm. The binary search algorithm is basically a divide and conquer algorithm which recursive divides the array into halves until it converses to a singleton element.
The sorting of array is necessary of binary search algorithm in this case, as it makes deciding which part to divide easy for us.
Example
const arr = [-3, -1, 4, 7, 9, 11, 14, 22, 26, 28, 36, 45, 67, 78, 88, 99]; const binarySearch = (arr = [], num) => { let l = 0; let r = arr.length - 1; while(l <= r){ const mid = Math.floor((l + r) / 2); if(num == arr[mid]){ return mid; } else if(num < arr[mid]){ r = mid - 1; } else{ l = mid + 1; }; }; return -1 }; console.log(binarySearch(arr, 22)); console.log(binarySearch(arr, 56)); console.log(binarySearch(arr, 11));
Output
And the output in the console will be −
7 -1 5