Background
I currently have an array like this:
[1,1,2,3,4,5,5,5,6,7,8,8,8,8,9,10]
I have been using a great JS Binary Search formula from this website:
searchArray = function(needle, haystack, case_insensitive) {
if (typeof(haystack) === 'undefined' || !haystack.length) return -1;
var high = haystack.length - 1;
var low = 0;
case_insensitive = (typeof(case_insensitive) === 'undefined' || case_insensitive) ? true:false;
needle = (case_insensitive) ? needle.toLowerCase():needle;
while (low <= high) {
mid = parseInt((low + high) / 2)
element = (case_insensitive) ? haystack[mid].toLowerCase():haystack[mid];
if (element > needle) {
high = mid - 1;
} else if (element < needle) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
};
This works fine for returning a single value.
Question
How do I return a range rather than a single value? For example, how would I return all values of 8 from the array, but STILL use the binary search (I do not want to loop through everything!!).
Thanks!
Something like this? http://jsfiddle.net/DCLey/3/