iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐈

Understanding the Essence of Binary Search via Abstraction: Going Beyond the Meguru-style with Higher-Order Functions

に公開
2025/08/20

0. Greetings

Hello, I'm somnicattus. I'm a software engineer who uses TypeScript.

I've published a TypeScript library "binary-search-generalized" that generalizes the binary search algorithm with higher-order functions.

This library provides a general-purpose binary search function that further generalizes the "Meguru-style binary search" — a well-known generalization of binary search — using higher-order functions.

In this article, I'll record my thoughts while creating the library, focusing on understanding the binary search algorithm and how to reuse code with higher-order functions.

This article is intended for:

  • Those who want a deeper understanding of the binary search algorithm.
  • Those interested in code reuse through higher-order functions.

1. What Is Binary Search?

Binary search is a method of finding a target value by repeatedly narrowing the search range in half. I think it's one of the most memorable algorithms encountered early in computer science.

Textbooks often use it for searching sorted arrays, but the essence of binary search is not array searching.
Binary search is an algorithm that, for a condition that has exactly one boundary value where truth flips within a range over a set of numbers being searched, identifies that boundary value.

In the Japanese competitive programming community, this abstraction is known as "Meguru-style binary search." I'll leave a detailed explanation to the following article:

https://qiita.com/drken/items/97e37dd6143e33a64c8c

When creating the library, I looked for predecessors who had thought about similar ideas, but searching for "binary search higher-order function" turned up no relevant libraries or technical articles.

The key points in abstracting binary search are:

  • Monotonicity: The predicate changes monotonically within the search range, dividing it into an always-true region and an always-false region with a single boundary.
  • Convergence: A midpoint of the search range can be calculated, and by repeatedly halving the range, the search converges within a given epsilon.

In binary-search-generalized, this idea is generalized and organized into a form where each element (predicate, always, never, midpoint, epsilon) can be injected and reused as arguments, making it reusable in programs.

3. Implementation of Generalized Binary Search with Higher-Order Functions

A higher-order function is a function that takes functions as arguments or returns a function.
In JavaScript/TypeScript, functions are first-class objects, so the "behavior" of binary search — such as the predicate or how the midpoint is chosen — can be passed as arguments and swapped out.
I'll leave a detailed explanation of higher-order functions to the following MDN documentation or explanatory articles:

https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function

Below is a simplified/adapted implementation of binarySearch, the core of the binary-search-generalized library:

/** Generalized binary search that injects monotonicity (always/never) and convergence (midpoint/epsilon) */
export function binarySearch(
  alwaysEnd: number,
  neverEnd: number,
  predicate: (value: number) => boolean,
  midpoint: (always: number, never: number) => number,
  epsilon: number,
): number {
  // Variables to track the current search range
  let always = alwaysEnd;
  let never = neverEnd;

  // Continue searching until the interval width is within epsilon
  while (Math.abs(always - never) > epsilon) {
    // Calculate the midpoint and evaluate the predicate at that point
    const mid = midpoint(always, never);
    // Based on the result, narrow the range by updating either always or never
    if (predicate(mid)) always = mid;
    else never = mid;
  }

  // Return the boundary value on the always side (we could return never, but this is clearer)
  return always;
}

Below is an explanation of the abstraction elements of this function.

Monotonic Condition and Its Range (predicate/always/never)

predicate provides the condition expression to be searched.
This condition must have exactly one boundary value (the point separating the always-true region from the always-false region) within the range specified by alwaysEnd and neverEnd.
Binary search is an algorithm that searches for this boundary value of the predicate.

alwaysEnd and neverEnd are values that are known to make the condition predicate true or false, respectively. These two values define the search range [alwaysEnd, neverEnd) or (neverEnd, alwaysEnd]. Within this range, the truth value of predicate flips exactly once.

This abstraction allows us to search for the boundary for any monotonic condition and range, as in the following examples:

  • Find the smallest integer n in the range 10 < n <= 100 such that n^2 >= 160.
  • Find the largest number x in the range -π/2 <= x < π/2 such that sin(x) <= 0.5.
  • Find the largest index in a sorted array arr such that the element at that index is <= 10.

Convergence and Termination Condition (midpoint/epsilon)

midpoint gives the central value mid that bisects the search range between always and never.
mid is evaluated with predicate, and based on the result, either always or never is replaced with mid, narrowing the range.
This operation must eventually converge the search range to within epsilon. Usually, mid = (always + never) / 2.

epsilon gives the acceptable error. When the distance between always and never becomes less than epsilon, the search terminates. For integers, epsilon = 1.

This abstraction allows binary search to be performed on any set of numbers:

  • For searching integers, midpoint should always return an integer (e.g., using floor), and epsilon = 1.
  • For searching even numbers, midpoint should always return an even value, and epsilon = 2.
  • For searching real numbers, midpoint can simply be the arithmetic mean, and epsilon is set to the desired precision (e.g., 5e-3).

4. Using the Generalized Binary Search (Array Search)

Applying the generalized function to array search yields the following:

  • Set of numbers to search: The indices of the sorted array.
  • Condition: Whether the element value at a given index is less than or equal to the target or not.
  • Single boundary value where truth flips within the range: The index where elements ≤ target and elements > target are adjacent.

Note that the array elements are not the search target; they are part of the condition array[i] <= target. The search target is always the index.

Representing binary search on an ascending array using the function arguments:

Argument Value Description
predicate (index) => arr[index] <= target The element at that index is less than or equal to the target
alwaysEnd -1 Specifies one position outside the index range, considering the possibility that the first element is greater than target[1]
neverEnd arr.length Specifies one position outside the index range, considering the possibility that the last element is less than target[1:1]
midpoint (always, never) => Math.floor((always + never) / 2) Must always return an integer, so we apply the floor function
epsilon 1 The minimum difference between distinct integers

Applying the above conditions gives the following code:

const arr = [0, 1, 1, 2, 3, 5, 8, 13, 21];
const target = 10;

const maybeTargetIndex = binarySearch(
  -1,
  arr.length,
  (index) => arr[index] <= target,
  (always, never) => Math.floor((always + never) / 2),
  1,
);

console.log(maybeTargetIndex); // 6
console.log(arr[maybeTargetIndex]); // 8

5. Specialization via Partial Application

Partial application is a technique where we fix some of the arguments of a multi-argument function to obtain a new function.

For example, by binding midpoint = (a, n) => Math.floor((a + n) / 2) and epsilon = 1 to binarySearch(), we can easily create a binary search function specialized for integers.

I'll leave a detailed explanation to the following article:

https://www.okb-shelf.work/entry/partial_and_curry

Below is an example of defining a function specialized for arrays using partial application (partially omitted/adapted).

/** Binary search for arrays */
const binarySearchArray = <T extends number | bigint | string>(
  array: readonly T[],
  target: T
): number => {
  // Condition that absorbs the difference between ascending and descending order
  const predicate = array[0] < array[array.length - 1]
    ? (index) => array[index] <= target
    : (index) => array[index] >= target;

  // Partial application of the general binary search
  const index = binarySearch(
    -1,
    array.length,
    predicate,
    (always, never) => Math.floor((always + never) / 2),
    1,
  );
  
  // Return -1 if not found
  if(index === -1 || array[index] !== target) return -1;
  return index;
}

// Usage example
const arr = ['apple', 'banana', 'cherry'];
const target = 'cherry';
const index = binarySearchArray(arr, target);

console.log(index); // 2

The original binarySearch has too many arguments and is overly general, but by partially applying arguments like this, we can define practical functions with a certain degree of generality.

In binary-search-generalized, we also provide functions specialized for integers, double-precision floating-point numbers, big integers, and arrays using partial application.

6. Further Generalization

Binary search can be generalized even further.

Searching Arbitrary Data with a Defined Ordering

By taking a comparator function comparator as an argument, we can search over any data that has a defined ordering, not just numbers.

This is also implemented in binary-search-generalized.

Searching with Multidimensional Conditions

For conditions with two or more monotonic axes, we can specify a rectangular range (rectangle, cuboid, etc.) and compute the "boundary line" or "boundary surface."

We are considering implementing this in binary-search-generalized in the future.

7. Summary

The essence of binary search is "identifying the boundary of a monotonic condition." If we can articulate predicate/always/never and midpoint/epsilon, we can solve problems beyond array searching with the same type of thinking.

By offloading behavior into arguments of a general-purpose higher-order function and assembling practical specialized functions through partial application, we can build small and reuse widely.

Comments on the article, PRs/Issues on the library are welcome. Happy searching (closing greeting thought of by GPT-5).

P.S. I tried leaving some of the writing to GPT-5, but ended up writing most of it myself. I realized that ultimately, only I can articulate what I want to convey.

References & Citations

binary-search-generalized

Cited Articles & Materials

脚注
  1. The two specified endpoints are never evaluated, so specifying values outside the array indices is not a problem. ↩︎ ↩︎

Discussion