2 mins read


Binary Search


Series: Search Algorithms

Episodes: (2/2)

Implementation

class BinarySearch<T> {
  private items: T[] = [];
 
  constructor(items: T[]) {
    this.items = items;
  }
 
  search(val: T): number {
    let left = 0;
    let right = this.items.length - 1;
 
    while (left <= right) {
      const mid = (left + right) >>> 1;
      // Check if target is present at mid
      if (this.items[mid] === val) {
          return mid;
      }
      // If target is greater, ignore left half
      if (this.items[mid] < val) {
          left = mid + 1;
      }
      // If target is smaller, ignore right half
      else {
          right = mid - 1;
      }
    }
    // If target is not present in the array
    return -1;
  }
}

Note:- (left + right) >>> 1 is a bitwise operation used to calculate the midpoint between two integers left and right without risking an integer overflow, and it's commonly used in binary search algorithms