Skip to content

Instantly share code, notes, and snippets.

@robertleeplummerjr
Last active January 4, 2023 18:41
Show Gist options
  • Save robertleeplummerjr/1cc657191d34ecd0a324 to your computer and use it in GitHub Desktop.
Save robertleeplummerjr/1cc657191d34ecd0a324 to your computer and use it in GitHub Desktop.
Ultra performant binary search to find nearest less than a value
function indexOfNearestLessThan(array, needle) {
if (array.length === 0) return -1;
var high = array.length - 1,
low = 0,
mid,
item,
target = -1;
if (array[high] < needle) {
return high;
}
while (low <= high) {
mid = (low + high) >> 1;
item = array[mid];
if (item > needle) {
high = mid - 1;
} else if (item < needle) {
target = mid;
low = mid + 1;
} else {
return low;
}
}
return target;
}
@zaycker
Copy link

zaycker commented Jan 4, 2023

return mid; instead of return low;

@robertleeplummerjr
Copy link
Author

I could be wrong but: indexOfNearest Less Than.

@zaycker
Copy link

zaycker commented Jan 4, 2023

yeah, sorry. After a moment I understood that my task is less or equal :)
Thank you!!!

@robertleeplummerjr
Copy link
Author

🙇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment