+ 1

Binary search using recursion

This program is not running on turbo c. When I enter a number to be searched which is not present in the array still it shows that the number is present in the array. https://code.sololearn.com/cj5oTh03Y1UE/?ref=app

15th Aug 2018, 11:06 PM
harshit
harshit - avatar
12 odpowiedzi
+ 8
You complain 2 isn't in the array as you use 0 as missing. Your if where n is set to -1 won't ever be entered as the only path that executes it is when the number was found. Delete that if, initialize n to -1, and test h against -1 in main.
16th Aug 2018, 6:18 PM
John Wells
John Wells - avatar
+ 8
Turbo C is obsolete and I've never used it (only GNU) so I'm not sure I can help with it. However, you are returning an uninitialized n in bs, if l is greater than r, so that could be the issue.
16th Aug 2018, 5:54 PM
John Wells
John Wells - avatar
+ 5
The x[m] != y is returned directly from the recursion so it can't get there. When y isn't in x, the recursion stops when l>r so never gets to that code as it is within l<=r if. The only code that executes the if is when x[m] = y, which won't enter it.
16th Aug 2018, 7:12 PM
John Wells
John Wells - avatar
+ 4
it is working
16th Aug 2018, 2:30 AM
code learner
code learner - avatar
+ 2
Thank you so much sir.
16th Aug 2018, 7:32 PM
harshit
harshit - avatar
+ 1
but it is not working in turbo c
16th Aug 2018, 8:11 AM
harshit
harshit - avatar
+ 1
John Wells sir, please see this also.
16th Aug 2018, 5:45 PM
harshit
harshit - avatar
+ 1
Yes it is working perfectly. But I don't understand why the if statement where n is set to -1 won't ever entered.
16th Aug 2018, 6:59 PM
harshit
harshit - avatar
+ 1
Also: you should format your source and give variables meaningful names.
16th Aug 2018, 10:50 PM
non
0
harshit which missing number you tried and it gave wrong output? For me also, it works for 3 to 4 missing numbers I tried
16th Aug 2018, 5:42 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
This code is not working in turbo c properly.
16th Aug 2018, 5:45 PM
harshit
harshit - avatar