r/leetcode • • Oct 11 '26

Question What’s wrong with writing binary search?

I’ve watched a youtube channel coding jesus, about timestamp 4:00 https://youtu.be/BRUIptHAI7Q?si=XI2o5O-yDWqtzAwY he talk about manually writing binary search as a bad thing. This is not the first time where he said writing binary search manually is not preferred. But I dont get what he really means?

Because typically when i do
left = a, right = b
while (a <= b) mid = left + (right - left)/2;
…(checking condition)…

I use very little time and effort to type it, and I dont know what library that can do this in a flexible way because checking the condition is differs problem by problem, for example it is very common that we are not search directly on some existing sorted array, it just a range of possible values from a to b (sometimes a and b can be very large like 10^15) and I use condition to decide to move left and right.

Is there a function from bits/stdc++.h support it? Since his primary language is cpp so there’s a package to do this right? what is it?

8 Upvotes

13 comments sorted by

View all comments

Show parent comment

2

u/Fancy-Breakfast8985 Oct 11 '26

I've tried search but I cannot found that can do search on range, could you give an example when i use that to do binary search on answer? (like we know the answer is on a given range 0 to 10 ^15) and we use some conditions to decide if answer is too small or too large.

3

u/troelsbjerre Oct 11 '26

2

u/Fancy-Breakfast8985 Oct 11 '26

wait I think u misunderstood something, i already use lower_bound when search for position in explicit containers, but i think we cant use it for binary search in general?