Algorithms and data structures for JS/TS
  • Introduction
  • GETTING STARTED
    • TS
    • Node.js
    • ES Modules
    • Browsers
  • PUBLIC API
    • How to read
    • Linked lists
      • SinglyLinkedList
      • DoublyLinkedList
      • CircularlyLinkedList
    • Stacks and queues
      • LinkedStack
      • LinkedQueue
      • LinkedDeque
      • CircularQueue
      • CircularArrayBuffer
      • UnsortedPriorityQueue
      • SortedPriorityQueue
      • AdaptableHeapPriorityQueue
    • Maps
      • SortedMap
      • MaximaSet
      • AVLTreeMap
      • SplayTreeMap
      • RedBlackTreeMap
    • Trees
      • GeneralTree
      • LinkedBinaryTree
      • PreorderTreeTraversal
      • InorderTreeTraversal
      • PostorderTreeTraversal
      • EulerTourTreeTraversal
    • Searches
      • Binary search
      • Quick select
    • Text processing
      • Longest common subsequence
      • Boyer-Moore
      • Knuth-Morris-Pratt
    • Position
    • Locator
    • Comparators
  • CONTRIBUTION NOTES
    • How to contribute
    • Project structure
  • Changelog
Powered by GitBook
On this page

Was this helpful?

  1. PUBLIC API
  2. Searches

Binary search

Implementation of a search algorithm on a sorted array which looks up for the specified value by repeatedly dividing the search interval in half.

binarySearch()

/**
 * Finds item in sorted array greater than or equal to the specified target.
 *
 * @param arr Array to search in.
 * @param target Search target.
 * @param from Index to start search from (inclusive). Will start from 0 by default.
 * @param to Index to stop search at (exclusive). Will examine the whole array by default.
 * @param compare Comparison function. Items are compared as numbers by default.
 * @returns Object with 'index' field representing an item the search has stopped at
 * and 'exact' field telling whether the target was matched exactly.
 */
function binarySearch<T, K = T>(
  arr: T[],
  target: K,
  from?: number,
  to?: number,
  compare: CompareFunc<T, K> = compareAsNumbers,
): { index: number, exact: boolean };

Finds item in sorted array greater than or equal to the specified target.

PreviousSearchesNextQuick select

Last updated 5 years ago

Was this helpful?