[英]fastest way to determine if an element is in a sorted array
我有一個包含1000個或更多值的排序整數數組(最多可以有5000個以上)。 我需要編寫一個函數,該函數接收一個int並根據數組中的元素返回一個布爾值。 我知道我可以用中斷來編寫for循環,也可以使用jquery .InArray。
知道對數組進行排序是實現此目的的最佳方法是什么。
謝謝。
知道數組已排序是二進制搜索將是最好的方法。
我認為您想使用二進制搜索例程。 二進制搜索例程是 而線性搜索平均而言, 。
有多種選擇形式。 這是我在本文中找到的:
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;
}
或者從這個簡單的版本看這篇文章已經在無數個不同語言的二進制搜索功能。
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;
}
Google閉包中也有一個二進制搜索,其中的代碼在此處 。
並且,很好地描述了二進制搜索算法如何在Wikipedia上工作 。
如果數組已排序,則答案也已排序-使用二進制印章。
如果查找不止一次,請遷移到類似地圖的對象。
var fastLookup = {}; mySortedArray.forEach(function(i){fastLookup[i]=true)}); //Each time: if (fastLookup[key]===true){ //do thing }
許多語言已經在Java中實現了此功能,例如,您可以只使用CollectionsCollections.binarySearch(List> list,T key)方法,而且我很確定C#也具有某種BinarySearch方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.