Skip to content

Instantly share code, notes, and snippets.

@fedeghe
Last active April 4, 2022 09:52
Show Gist options
  • Save fedeghe/d73d6a53268d81b0df74db99efdeb19f to your computer and use it in GitHub Desktop.
Save fedeghe/d73d6a53268d81b0df74db99efdeb19f to your computer and use it in GitHub Desktop.
find insert index in a sorted array
/**
* 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