Answers for "binary search javascript"

7

javascript binary search

const arr = [1, 3, 5, 7, 8, 9];
const binarySearch = (arr, x , start=0, end=arr.length) => {
  // If the item does not exist, return -1
  if(end < start) return -1;
  
  // Calculate middle index of the array
  let mid = Math.floor((start + end) / 2);
  
  // Is the middle a match?
  if(arr[mid] === x) return mid;
  // Is the middle less than x
  if(arr[mid] < x) return binarySearch(arr, x, mid+1, end);
  // Else the middle is more than x
  else return binarySearch(arr, x , start, mid-1);
}

binarySearch(arr, 7); // Returns 3
/* O(n) of binarySearch is log(n) */
Posted by: Guest on February-28-2021
2

how to get binary value of int javascript

const convertNumberToBinary = number => {
    return (number >>> 0).toString(2);
}
Posted by: Guest on May-28-2020
0

binary search in js

function binarySearch(arr, val) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

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

    if (val < arr[mid]) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }
  return -1;
}
Posted by: Guest on September-15-2021
5

binaryserachindex javascript

function binarySearchIndex (array, target, low = 0, high = array.length - 1) {
  if (low > high) {
    return -1
  }
  const midPoint = Math.floor((low + high) / 2)

  if (target < array[midPoint]) {
    return binarySearchIndex(array, target, low, midPoint - 1)
  } else if (target > array[midPoint]) {
    return binarySearchIndex(array, target, midPoint + 1, high)
  } else {
    return midPoint
  }
}
Posted by: Guest on April-08-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language