DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {boolean}
 */
var search = function (arr, target) {
  let low = 0;
  let high = arr.length - 1;

  while (low <= high) {
    let mid = parseInt((low + high) / 2);

    if (arr[mid] === target) {
      return true;
    }

    // check search in first Half & as low  < mid mean it is sorted
    if (arr[mid] === arr[high]) {
      high--;
    } else if (arr[low] <= arr[mid]) {
      if (target <= arr[mid] && target >= arr[low]) {
        high = mid - 1;
      } else {
        low = mid + 1;
      }
    } // check search in 2nd Half
    else {
      if (target <= arr[high] && target >= arr[mid]) {
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }
  }

  return false;
};
console.log(search([2, 5, 6, 0, 0, 1, 2], 3));
console.log(search([1, 0, 1, 1, 1], 0));
console.log(search([3, 1], 1));


Enter fullscreen mode Exit fullscreen mode

Top comments (0)