Skip to content

Commit

Permalink
fix(arrays): fixed-length binarySearch2/4/8/16/32
Browse files Browse the repository at this point in the history
- add binarySearch2()
- fix results for not-found values, make compatible w/ binarySearch()
  • Loading branch information
postspectacular committed Jan 21, 2021
1 parent be3e43d commit 39e5c37
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/arrays/src/binary-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ export const binarySearchNumeric = (
return -low - 1;
};

export const binarySearch2 = (buf: ArrayLike<number>, x: number) => {
let idx = buf[1] <= x ? 1 : 0;
return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1;
};

/**
* Non-recursive, optimized binary search for fixed size numeric arrays of 4
* values. Returns index of `x` or `-index-1` if not found.
Expand All @@ -96,7 +101,7 @@ export const binarySearchNumeric = (
export const binarySearch4 = (buf: ArrayLike<number>, x: number) => {
let idx = buf[2] <= x ? 2 : 0;
idx |= buf[idx + 1] <= x ? 1 : 0;
return buf[idx] === x ? idx : -idx - 1;
return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1;
};

/**
Expand All @@ -110,7 +115,7 @@ export const binarySearch8 = (buf: ArrayLike<number>, x: number) => {
let idx = buf[4] <= x ? 4 : 0;
idx |= buf[idx + 2] <= x ? 2 : 0;
idx |= buf[idx + 1] <= x ? 1 : 0;
return buf[idx] === x ? idx : -idx - 1;
return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1;
};

/**
Expand All @@ -125,7 +130,7 @@ export const binarySearch16 = (buf: ArrayLike<number>, x: number) => {
idx |= buf[idx + 4] <= x ? 4 : 0;
idx |= buf[idx + 2] <= x ? 2 : 0;
idx |= buf[idx + 1] <= x ? 1 : 0;
return buf[idx] === x ? idx : -idx - 1;
return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1;
};

/**
Expand All @@ -141,7 +146,7 @@ export const binarySearch32 = (buf: ArrayLike<number>, x: number) => {
idx |= buf[idx + 4] <= x ? 4 : 0;
idx |= buf[idx + 2] <= x ? 2 : 0;
idx |= buf[idx + 1] <= x ? 1 : 0;
return buf[idx] === x ? idx : -idx - 1;
return buf[idx] === x ? idx : buf[0] < x ? -idx - 2 : -1;
};

/**
Expand Down

0 comments on commit 39e5c37

Please sign in to comment.