function binarySearch(items, target){
var startIndex = 0,
stopIndex = items.length-1,
middle = Math.floor((stopIndex+startIndex)/2);
debugger;
while(items[middle]!=target && startIndex<stopIndex){
if(target<items[middle]){
stopIndex = middle-1;
} else if(target>items[middle]){
startIndex = middle+1;
}
middle = Math.floor((stopIndex+startIndex)/2);
}}
我编写了另一个函数来使用上面的binarySearch(),这个函数是
function getValue(){
var items = ["a","b","c","d","e","f","g","h","i","j"];
alert(binarySearch(items,"i"));}
我像这样从 HTML 调用 getValue()
<button onclick="getValue()">Click to find the binary</button>
当我单击该按钮时,它会提醒“取消定义”。
实际上,我正在学习,所以我无法正确理解如何传递值,如何调用函数来获取期望值。 如果有人帮助我理解并解决这个问题,我将不胜感激。
最佳答案
您的函数没有返回任何内容。循环运行完成后,您需要返回找到的内容。
function binarySearch(items, target){
var startIndex = 0,
stopIndex = items.length-1,
middle = Math.floor((stopIndex+startIndex)/2);
debugger;
while(items[middle]!=target && startIndex<stopIndex){
if(target<items[middle]){
stopIndex = middle-1;
} else if(target>items[middle]){
startIndex = middle+1;
}
middle = Math.floor((stopIndex+startIndex)/2);
}
return (items[middle] !== target) ? -1 : middle;
}
返回行使用 ternary运算符,它相当于 if 语句。
关于javascript - JavaScript BinarySearch 的未定义结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649093/