Last active
April 4, 2022 09:52
-
-
Save fedeghe/d73d6a53268d81b0df74db99efdeb19f to your computer and use it in GitHub Desktop.
find insert index in a sorted array
This file contains 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
/** | |
* Implements in place binary search. O(log n) | |
* optional comparator can be passed | |
*/ | |
function findInsertIndex(a, item, smaller) { | |
var l = 0, | |
len = a.length, | |
r = len - 1, | |
m; | |
smaller = smaller || function(a, b, strict){ | |
return strict ? a < b : a <= b; | |
}; | |
if (len === 0) return 0 | |
while (true) { | |
if (smaller(item, a[l], true)) return l; | |
if (smaller(a[r], item, true)) return r+1; | |
if (l === r-1 && smaller(a[l], item) && smaller(item, a[r])) return r | |
m = Math.floor((r + l) / 2); | |
if (item <= a[m]) r = m | |
else l = m | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment