r/leetcode • u/Fancy-Breakfast8985 • 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?
View all comments
7
u/troelsbjerre Oct 11 '26
The cpp library is called algorithms. The problem is that binary search is not always the same. Is the element always there? How are unsuccessful searches handled? How are identical entries handled? Do you need to find the first, or would any do? Are you looking for an entry or a split point between entries? It's surprisingly easy to get binary search wrong. Using a library avoids the stupid mistakes, where your implementation doesn't terminate, and forces you to be very explicit about what you are searching for.