Searching for a query using binary search in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a sorted array of literals as the first argument and a query literal as second. Then our function should make use of the Binary Search algorithm to find whether the query exists in the array or not.

If it exists, we return its index in the array, otherwise we return -1.

Example

The code for this will be −

const arr = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
const binarySearch = (arr, query) => {
   let index = Math.floor(arr.length / 2);
   if (arr[index] === query){
      return index;
   }else if (arr.length === 1){
      return null;
   }else if (arr[index] < query) {
      arr = arr.slice(index + 1);
      let res = binarySearch(arr, query);
      if (res === null){
         return -1;
      }else {
         return index + 1 + res;
      };
   }else {
      let arr1 = arr.slice(0, index);
      return binarySearch(arr1, query);
   };
};
console.log(binarySearch(arr, 1));
console.log(binarySearch(arr, 7));
console.log(binarySearch(arr, 11));
console.log(binarySearch(arr, 12));
console.log(binarySearch(arr, 22));

Output

The output in the console −

0
5
7
-1
13
raja
Published on 17-Oct-2020 09:02:35
Advertisements