Switching to JS for some interviews, so practicing building structures/sorting/search.
Making a simple Binary Search that returns true if the array contains the value. I'm aware that it freaks out if the array doesn't contain the value, but I'm currently trying to address why what's getting logged in my console is "undefined" instead of "true" when I run this simple implementation. Any thoughts?
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);