我似乎無法讓此代碼正常工作。如果它們的鍵在數組中,則代碼應該提示True,如果它不在數組中,它應該提示false。我似乎無法做到。謝謝!JavaScript中的二進制數組搜索
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Search</title>
<script type="text/javascript">
function testFunction() {
var list = [ 1, 2, 3, 4, 5, 6, 7 ];
var key = 9;
var result1 = 0;
//var result2 = 0;
result1 = search(list, key);
}
function search(list, key) {
var left = 0;
var right = list.length - 1;
while (left <= right) {
var mid = left + ((right - left) >>> 1);
var cmp = key - list[mid];
if (cmp > 0){
left = alert("True");
} else if (cmp < 0){
alert("False");
}else {
return mid;
}
return mid;
}
}
</script>
</head>
<h1>Search:</h1>
<button type="button" onclick="testFunction()">Volume</button>
<div id="outputDiv"></div>
</html>
我敢寫這樣的比較版本確定'>>>'不正確...只需使用'>' – Markasoftware
爲什麼不只是'list.indexOf(key)'? –
是的,這對於你想要做的事似乎太複雜了。只要在搜索功能中執行'return list.indexOf(key)!== - 1',沒有其他任何東西 – Markasoftware