Intro

A common pattern, that utilizes a left and right pointer to half the list or array step by step. // For BinarySearchTree see Trees.

How it works

  1. Start by checking if middle element is the target
    1. If yes then success and return
  2. If target is greater than middle, then set the left ptr to the element at the index of the middle + 1.
  3. If target is less than middle, then set the right ptr to the element at the index of the middle - 1.

Since we’re halving the search zone each time, it’s very efficient, with a time complexity of O(log(n))

Binary Search and Monotonic Functions

Can be used on any collection that utilizes a MonotonicFunction (function that either always increases or always decreases (or remains constant) over its entire domain) so can be used on any condition used for sorting, not just numbers.

Examples