Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
1 change: 1 addition & 0 deletions collections/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"./take-last-while": "./take_last_while.ts",
"./take-while": "./take_while.ts",
"./union": "./union.ts",
"./unstable-binary-search": "./unstable_binary_search.ts",
"./unstable-chunk": "./unstable_chunk.ts",
"./unstable-cycle": "./unstable_cycle.ts",
"./unstable-drop-while": "./unstable_drop_while.ts",
Expand Down
55 changes: 55 additions & 0 deletions collections/unstable_binary_search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
* Binary search within a sorted array, allowing for non-exact matches.
*
* Binary searching may be preferable to `Array#findIndex` if the array is
* large and performance is at a premium, or if information about the insertion
* index is needed upon non-exact matches (`Array#findIndex` simply returns
* `-1` in such cases).
Comment on lines +7 to +10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

*
* @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.
*
* @example Usage
* ```ts
* import { binarySearch } from "@std/collections/unstable-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/unstable_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 "./unstable_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);
}
});
});
Loading