Created
June 5, 2015 17:05
-
-
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
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
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