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())

30th Oct 2021, 7:55 AM
Aniket Ganguly
7 Antworten
+ 1
Aniket Ganguly Because you didn't return any value
30th Oct 2021, 8:13 AM
A͢J
A͢J - avatar
+ 3
Aniket Ganguly Yes you have returned but what if that condition will not execute? There is no guarantee that condition will execute?
30th Oct 2021, 8:28 AM
A͢J
A͢J - avatar
+ 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 = )
30th Oct 2021, 8:27 AM
Kashyap Kumar
Kashyap Kumar - avatar
0
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ but I return mid in if statement see😀
30th Oct 2021, 8:15 AM
Aniket Ganguly
0
Hmm
30th Oct 2021, 8:30 AM
Aniket Ganguly
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.
30th Oct 2021, 8:32 AM
PanicS
PanicS - avatar
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
31st Oct 2021, 4:55 AM
sree harsha
sree harsha - avatar