I think you'd want to use a binary search routine. A binary search routine is
whereas a linear search is, on average,
.
There are many variations to choose form. Here's one I found in this article:
function binarySearch(items, value){
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -1 : middle;
}
Or this simpler looking version from this article that has a binary search function in a zillion different languages.
function binary_search_iterative(a, value) {
var lo = 0, hi = a.length - 1, mid;
while (lo <= hi) {
mid = Math.floor((lo+hi)/2);
if (a[mid] > value)
hi = mid - 1;
else if (a[mid] < value)
lo = mid + 1;
else
return mid;
}
return null;
}
There's also a binary search in Google closure with the code here.
And, a good description of how the binary search algorithm works on Wikipedia.