Answer the question
In order to leave comments, you need to log in
Why is the result output as undefined?
Wrote a recursive implementation of a binary search, but the position of the element is not displayed. Why?
function test(list, guess, low=0, hight=list.length-1){
mid = parseInt((low+hight)/2);
// console.log("low = "+low+" hight = "+hight+" mid = "+parseInt(mid+1));
if (list[mid]==guess){
console.log("Вывод "+parseInt(mid+1)); //<------ вывод проходит верно
return mid+1;
};
if (low==hight){
//console.log(2);
return -1;
};
test(list, guess, (list[mid]<guess) ? mid+1 : low, (list[mid]>guess) ? mid-1 : hight);
}
a = test([2,4,4,6,8,12,15],15);
console.log(a); // undefined
Answer the question
In order to leave comments, you need to log in
Because you are not returning anything from the function.
And under the conditions of others, apparently it does not fit where there is a return mid + 1 or -1
When returning from recursion, the result returned from the test function is not used in any way.
Try writing:
return test(list, guess, (list[mid]guess) ? mid-1 : hight);
And for your example, you will end up in a branch:
if (list[mid]==guess){
console.log("Output "+parseInt(mid+1)); //<------ the output is correct
return mid+1;
};
and mid will be equal to 6, i.e. 6+1 = 7 will arrive from the function, which goes beyond the array boundary.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question