Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions collections/binary_search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
* A binary search that accounts for non-exact matches.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @typeParam T The type of `haystack`.
*
* @param haystack The array to search. This MUST be sorted in ascending order, otherwise results may be incorrect.
* @param needle The value to search for.
* @returns
* - If `needle` is matched exactly, the index of `needle`. If multiple elements in `haystack` are equal to `needle`,
* the index of the first match found (which may not be the first sequentially) is returned.
* - Otherwise, the [bitwise complement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT)
* of `needle`'s insertion index if it were added to `haystack` in sorted order.
*
* Return value semantics are the same as C#'s [`Array.BinarySearch`](https://learn.microsoft.com/en-us/dotnet/api/system.array.binarysearch#system-array-binarysearch(system-array-system-object))
* and Java's [`Arrays.binarySearch`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#binarySearch-int:A-int-).
*
* @example Usage
* ```ts
* import { binarySearch } from "@std/collections/binary-search";
* import { assertEquals } from "@std/assert";
*
* assertEquals(binarySearch([0, 1], 0), 0);
* assertEquals(binarySearch([0, 1], 1), 1);
* assertEquals(binarySearch([0, 1], -0.5), -1); // (bitwise complement of 0)
* assertEquals(binarySearch([0, 1], 0.5), -2); // (bitwise complement of 1)
* assertEquals(binarySearch([0, 1], 1.5), -3); // (bitwise complement of 2)
* ```
*/
export function binarySearch<
T extends ArrayLike<number> | ArrayLike<bigint> | ArrayLike<string>,
>(
haystack: T,
needle: T[number],
): number {
let start = 0;
let mid: number;

for (
let end = haystack.length - 1;
start <= end;
haystack[mid]! < needle ? start = mid + 1 : end = mid - 1
) {
mid = Math.floor((start + end) / 2);
if (haystack[mid]! === needle) return mid;
}

return ~start;
}
107 changes: 107 additions & 0 deletions collections/binary_search_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright 2018-2025 the Deno authors. MIT license.
import { assertEquals } from "@std/assert";
import { binarySearch } from "./binary_search.ts";
import { assertSpyCalls, spy } from "@std/testing/mock";

Deno.test("binarySearch() gives exact or non-exact indexes", async (t) => {
await t.step("examples", () => {
assertEquals(binarySearch([0, 1], 0), 0);
assertEquals(binarySearch([0, 1], 1), 1);
assertEquals(binarySearch([0, 1], -0.5), -1); // -1 == ~0 (bitwise complement)
assertEquals(binarySearch([0, 1], 0.5), -2); // -2 == ~1 (bitwise complement)
assertEquals(binarySearch([0, 1], 1.5), -3); // -3 == ~2 (bitwise complement)
});

await t.step("0 elements", () => {
const arr: number[] = [];
assertEquals(binarySearch(arr, -1), -1);
assertEquals(binarySearch(arr, 0), -1);
assertEquals(binarySearch(arr, 1), -1);
});

await t.step("1 element", () => {
const arr = [0];
assertEquals(binarySearch(arr, -1), -1);
assertEquals(binarySearch(arr, 0), 0);
assertEquals(binarySearch(arr, 1), -2);
});

await t.step("even number of elements", () => {
const arr = [0, 1];
assertEquals(binarySearch(arr, -1), -1);
assertEquals(binarySearch(arr, -0.5), -1);
assertEquals(binarySearch(arr, 0), 0);
assertEquals(binarySearch(arr, 0.5), -2);
assertEquals(binarySearch(arr, 1), 1);
assertEquals(binarySearch(arr, 1.5), -3);
assertEquals(binarySearch(arr, 2), -3);
});

await t.step("odd number of elements", () => {
const arr = [0, 1, 2];
assertEquals(binarySearch(arr, -1), -1);
assertEquals(binarySearch(arr, -0.5), -1);
assertEquals(binarySearch(arr, 0), 0);
assertEquals(binarySearch(arr, 0.5), -2);
assertEquals(binarySearch(arr, 1), 1);
assertEquals(binarySearch(arr, 1.5), -3);
assertEquals(binarySearch(arr, 2), 2);
assertEquals(binarySearch(arr, 2.5), -4);
assertEquals(binarySearch(arr, 3), -4);
});

await t.step("bigints", () => {
const arr = [0n, 1n, 3n];
assertEquals(binarySearch(arr, -1n), -1);
assertEquals(binarySearch(arr, 0n), 0);
assertEquals(binarySearch(arr, 1n), 1);
assertEquals(binarySearch(arr, 2n), -3);
assertEquals(binarySearch(arr, 3n), 2);
});

await t.step("typed arrays", () => {
const arr = new Int32Array([0, 1, 3]);
assertEquals(binarySearch(arr, -1), -1);
assertEquals(binarySearch(arr, 0), 0);
assertEquals(binarySearch(arr, 1), 1);
assertEquals(binarySearch(arr, 2), -3);
assertEquals(binarySearch(arr, 3), 2);
});

await t.step("typing", () => {
void (() => {
// @ts-expect-error Argument of type 'number' is not assignable to parameter of type 'bigint'.
binarySearch([0n], 0);
// @ts-expect-error Argument of type 'bigint' is not assignable to parameter of type 'number'.
binarySearch([0], 0n);

// @ts-expect-error Argument of type 'undefined' is not assignable to parameter of type 'number'.
binarySearch([0], undefined);
});
});

await t.step("algorithm correctness - number of loop iterations", () => {
/** `Math.floor` calls act as a proxy for the number of loop iterations, as it's called once per iteration */
const spyLoopIterations = () => spy(Math, "floor");

const arr = Array.from({ length: 1_000_000 }, (_, i) => i);

{
using iterations = spyLoopIterations();
const searchVal = 499_999;
const result = binarySearch(arr, searchVal);

assertEquals(result, 499_999);
assertSpyCalls(iterations, 1);
}

{
using iterations = spyLoopIterations();
const searchVal = 499_999.1;
const result = binarySearch(arr, searchVal);

assertEquals(result, -500_001);
assertSpyCalls(iterations, 19);
}
});
});
1 change: 1 addition & 0 deletions collections/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"./aggregate-groups": "./aggregate_groups.ts",
"./associate-by": "./associate_by.ts",
"./associate-with": "./associate_with.ts",
"./binary-search": "./binary_search.ts",
"./chunk": "./chunk.ts",
"./deep-merge": "./deep_merge.ts",
"./distinct": "./distinct.ts",
Expand Down
1 change: 1 addition & 0 deletions collections/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
export * from "./aggregate_groups.ts";
export * from "./associate_by.ts";
export * from "./associate_with.ts";
export * from "./binary_search.ts";
export * from "./chunk.ts";
export * from "./deep_merge.ts";
export * from "./distinct.ts";
Expand Down
Loading