Class BinarySearch<T>

Binary Search algorithm Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item.

Time Complexity: O(log n) Space Complexity: O(1) for iterative, O(log n) for recursive

Example

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
BinarySearch.search(arr, 5); // returns 4 (index)
BinarySearch.search(arr, 10); // returns -1 (not found)

Example

const bs = new BinarySearch([1, 2, 3, 4, 5]);
bs.search(3); // returns 2 (index)

Type Parameters

  • T

Hierarchy

  • BinarySearch

Constructors

  • Type Parameters

    • T

    Parameters

    • array: T[] = []
    • comparator: ((a, b) => number) = BinarySearch.defaultComparator
        • (a, b): number
        • Parameters

          • a: T
          • b: T

          Returns number

    Returns BinarySearch<T>

Properties

comparator: ((a, b) => number)

Type declaration

    • (a, b): number
    • Parameters

      • a: T
      • b: T

      Returns number

values: T[]

Methods

  • Instance method to search for a target in the stored array

    Parameters

    • target: T

      element to search for

    Returns number

    index of the target element, or -1 if not found

  • Instance method to search recursively for a target in the stored array

    Parameters

    • target: T

      element to search for

    • left: number = 0
    • right: number = ...

    Returns number

    index of the target element, or -1 if not found

  • Static method to perform binary search on an array

    Parameters

    • array: any[]

      sorted array to search in

    • target: any

      element to search for

    • comparator: ((a, b) => number) = ...

      optional comparator function

        • (a, b): number
        • Default comparator function

          Parameters

          • a: any
          • b: any

          Returns number

    Returns number

    index of the target element, or -1 if not found

  • Static recursive method to perform binary search on an array

    Parameters

    • array: any[]

      sorted array to search in

    • target: any

      element to search for

    • comparator: ((a, b) => number) = ...

      optional comparator function

        • (a, b): number
        • Default comparator function

          Parameters

          • a: any
          • b: any

          Returns number

    • left: number = 0
    • right: number = ...

    Returns number

    index of the target element, or -1 if not found

Generated using TypeDoc