我在javascript中編寫了一個二進制搜索。爲什麼我的javascript二進制搜索錯誤?
Array.prototype.binarySearch = function(find) {
var low = 0, high = this.length - 1,
i;
while (low <= high) {
i = Math.floor((low + high)/2);
if (this[i] > find) { low = i; continue; };
if (this[i] < find) { high = i; continue; };
return i;
}
return null;
}
雖然在我的整數數組中找到5,但它失敗了。
var intArray = [1, 2, 3, 5]
if (intArray.binarySearch(5))
alert("found!");
else
alert("no found!");
這是一個小提琴。 http://jsfiddle.net/3uPUF/3/
,你從缺少''this'這個[我]' – 2012-03-15 03:03:35
哦謝謝。我沒有注意到這一點。 – dangerChihuahua007 2012-03-15 03:04:10
另外,爲什麼我必須用'Array.prototype.binarySearch'定義方法?爲什麼不'Array.binarySearch'工作? – dangerChihuahua007 2012-03-15 03:09:19