Tôi nghĩ bạn muốn sử dụng một thói quen tìm kiếm nhị phân. Một thói quen tìm kiếm nhị phân là trong khi tìm kiếm tuyến tính trung bình là .
Có nhiều biến thể để chọn biểu mẫu. Dưới đây là một tôi tìm thấy trong 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;
}
Hoặc tìm phiên bản này đơn giản hơn từ this article mà có một chức năng tìm kiếm nhị phân trong một zillion ngôn ngữ khác nhau.
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;
}
Ngoài ra còn có tìm kiếm nhị phân trong đóng cửa của Google với mã here.
Và mô tả tốt về cách thuật toán tìm kiếm nhị phân hoạt động trên Wikipedia.
Chắc chắn con đường để đi. http://en.wikipedia.org/wiki/Binary_search –
http://www.nczonline.net/blog/2009/09/01/computer-science-in-javascript-binary-search/ – Pete
ok, cảm ơn vì tiền boa! – frenchie