Skip to content

Instantly share code, notes, and snippets.

@edsykes
Created June 5, 2015 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edsykes/04fe7951a7e08fcec417 to your computer and use it in GitHub Desktop.
Save edsykes/04fe7951a7e08fcec417 to your computer and use it in GitHub Desktop.
find the index where a value would be inserted in a reverse sorted array
var reverseSortedIndex = function(array, value, predicate){
var result = -1;
var low = 0;
var high = array.length;
var current = 0;
var search = value;
while(low < high){
// uncomment these lines if you want to see how this algorithm works
//console.log('');
//console.log('low: ' + low);
//console.log('high: ' + high);
current = (high + low) >> 1;
//console.log('current: ' + current);
if(current >= array.length){
current = array.length;
break;
}
if(search >= predicate(array[current])){
high = current;
}
else if(search < predicate(array[current])){
low = current + 1;
}
else{
break;
}
}
result = low;
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment