0
Why I got undefined in binary search??
function binarysearch(){ var a=[1,2,3]; let start=0; let end=a.length-1; let mid=Math.floor(start+end /2); //1 let target=3; while(start<end) { if(a[mid]==target){ return mid } else if(target>a[mid]){ start=mid+1 } else { end=mid-1 } } } console.log(binarysearch())
7 Answers
+ 1
Aniket Ganguly
Because you didn't return any value
+ 3
Aniket Ganguly
Yes you have returned but what if that condition will not execute?
There is no guarantee that condition will execute?
+ 1
Because you put the line
let mid=Math.floor((start+end)/2); //1
outside the while loop. So, mid is always same even after changing the start and end.
Just put that line just before the if statement inside the while loop and change the condition of while loop to start<=end (you have missed the = )
0
A͢J - SÍoÍlÍoÍHÍeÍlÍpÍeÍrÍ but I return mid in if statement seeđ
0
Hmm
0
Your code inside else if is one what is executed. (You can place console.log() inside every if/else to find whats going on in your code. )
And inside this you dont return anything.
0
Initially, make sure that the array must be in ascending order
Then only we get the required output
It is the prerequisites of binary search