-
Notifications
You must be signed in to change notification settings - Fork 663
feat(collections/unstable): add non-exact binary search function #6628
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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). | ||
| * | ||
| * @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; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍