K
K
Kir2019-04-26 12:12:40
JavaScript
Kir, 2019-04-26 12:12:40

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

3 answer(s)
A
Alexander Aksentiev, 2019-04-26
@Sanasol

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

R
Ruslan., 2019-04-26
@LaRN

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.

0
0xD34F, 2019-04-26
@0xD34F

And the result of a recursive call should return itself, without your participation? No, it won't.
Add return:
UPD. And why the hell are you returning mid + 1 instead of mid when you find an element?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question