Skip to content

Commit

Permalink
feat(arrays): add binarySearchNumeric()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 11, 2019
1 parent 2b8fafc commit 7b38202
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions packages/arrays/src/binary-search.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Comparator, Fn } from "@thi.ng/api";
import { compare } from "@thi.ng/compare";
import { compare, compareNumAsc } from "@thi.ng/compare";

/**
* Returns the supposed index of `x` in pre-sorted array-like collection
* `buf`. If `x` can't be found, returns `-index-1`, representing the
* negative of the index were `x` to be inserted into `buf`. E.g if the
* negative of the index, were `x` to be inserted into `buf`. E.g if the
* return value is -3, `x` would appear/insert at index 2.
*
* ```
Expand Down Expand Up @@ -46,3 +46,33 @@ export const binarySearch = <A, B>(
}
return -low - 1;
};

/**
* Similar to `binarySearch()`, but optimized for numeric arrays and
* supporting custom comparators (default: `compareNumAsc` from
* thi.ng/compare pkg).
*
* @param buf
* @param x
* @param cmp
*/
export const binarySearchNumeric = (
buf: ArrayLike<number>,
x: number,
cmp: Comparator<number> = compareNumAsc
) => {
let low = 0;
let high = buf.length - 1;
while (low <= high) {
const mid = (low + high) >>> 1;
const c = cmp(buf[mid], x);
if (c < 0) {
low = mid + 1;
} else if (c > 0) {
high = mid - 1;
} else {
return mid;
}
}
return -low - 1;
};

0 comments on commit 7b38202

Please sign in to comment.