Searching in a sorted 2-D array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of arrays of numbers as the first argument and a number as the second argument. The subarrays contain numbers sorted in an increasing order and no element of a preceding subarray is greater than any element of the succeeding subarray.

The function should use the binary search algorithm to search for the element provided as the second argument in the sorted array of arrays.

If the element exists the function should return true, false otherwise.

For example −

If the input array is −

const arr = [
   [2, 6, 9, 11],
   [13, 16, 18, 19, 21],
   [24, 26, 28, 31]
];
const num = 21;

Then the output should be −

const output = true;

Example

Following is the code −

const arr = [
   [2, 6, 9, 11],
   [13, 16, 18, 19, 21],
   [24, 26, 28, 31]
];
const num = 21;
const search2D = (array = [], target) => {
   const h = array.length;
   const w = h > 0 ? array[0].length : 0;
   if (h === 0 || w === 0) { return false; }
   const arr = getArr();
   if (!arr) { return false; }
      return binarySearch(arr, target) !== null;
   function getArr() {
      for (let i = 0; i < h; i++) {
         let arr = array[i];
         if (arr[0] <= target && target <= arr[arr.length - 1]) {
            return arr;
         }
      }
      return null;
   }
   function binarySearch(arr, t) {
      let left = 0;
      let right = arr.length - 1;
      while (left <= right) {
         if (arr[left] === t) {
            return left;
         }
         if (arr[right] === t) {
            return right;
         }
         let mid = Math.floor((left + right) / 2);
         if (arr[mid] === t) {
            return mid;
         }
         if (arr[mid] < t) {
            left = mid + 1;
         }
         else if (arr[mid] > t) {
            right = mid - 1;
         }
      }
      return null;
   }
};
console.log(search2D(arr, num))

Output

Following is the console output −

true
raja
Published on 19-Jan-2021 06:20:19
Advertisements