Last active
January 4, 2023 18:41
-
-
Save robertleeplummerjr/1cc657191d34ecd0a324 to your computer and use it in GitHub Desktop.
Ultra performant binary search to find nearest less than a value
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
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; | |
} |
I could be wrong but: indexOfNearest
Less Than
.
yeah, sorry. After a moment I understood that my task is less or equal :)
Thank you!!!
🙇
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
return mid;
instead ofreturn low;