Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Created July 31, 2018 19:50
Show Gist options
  • Select an option

  • Save YozhEzhi/26bc17f38d1aeadad471fcd9a7d78f2d to your computer and use it in GitHub Desktop.

Select an option

Save YozhEzhi/26bc17f38d1aeadad471fcd9a7d78f2d to your computer and use it in GitHub Desktop.
Алгоритмы. Бинарный поиск. Бинарные деревья.

Работает только для отсортированных массивов.

function binarySearch(
  array,
  element,
  start = 0,
  end = array.length - 1,
) {
  if (end < start) return -1;
  
  const middle = Math.floor((start + end) / 2);

  return element === array[middle] ?
    middle :
      element < array[middle] ?
      binarySearch(array, element, start, middle - 1) :
      binarySearch(array, element, middle + 1, end);
}

console.log(binarySearch([3, 4, 5, 6, 7, 8, 9, 10], 5)); // 2
console.log(binarySearch([3, 4, 5, 6, 7, 8, 9, 10], 2)); // -1

Since in each recursive call we break down the search space in half, our problem size decreases exponentially, taking our worst case time complexity from O(n) to O(log n).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment