切换到JS进行一些访谈,以便练习建筑结构/排序/搜索。
进行简单的二进制搜索,如果数组包含值,则返回true。我知道如果阵列没有包含该值,它会吓坏我,但我现在正试图解决为什么我的控制台中记录的内容是"未定义&# 34;而不是" true"当我运行这个简单的实现。有什么想法吗?
var sortedarray = [1, 2, 4, 5];
//,10,23,34,45,56,78,88,98,123,64356];
var submitInt = 5;
function BinarySearch(inputArray, inputValue) {
var halflength = Math.floor(inputArray.length / 2);
console.log("halflength: " + halflength);
console.log("input value: " + inputValue);
var ArrayVal = inputArray[halflength];
console.log("element value: " + ArrayVal);
if (inputValue == ArrayVal) {
return true;
} else {
if (inputValue > inputArray[halflength]) {
var SecondhalfArray = [];
SecondhalfArray = inputArray.splice(halflength);
console.log("SecondHalfArray: " + SecondhalfArray);
BinarySearch(SecondhalfArray, inputValue);
} else {
var FirsthalfArray = [];
FirsthalfArray = inputArray.splice(0, halflength);
console.log("FirstHalfArray: " + FirsthalfArray);
BinarySearch(FirsthalfArray, inputValue);
}
}
}
var booltest = BinarySearch(sortedarray, submitInt);
console.log(booltest);