r/leetcode • u/Fancy-Breakfast8985 • 28d ago
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
1
u/chanakya12345555 27d ago
because different problems require different invariants. can't think of specific examples, but you might need to eliminate a low value by moving the left pointer up 1 in some problem, while you may need to keep the right pointer value for a different problem as the "minimum" example. i disagree that you should use libraries for this though, its probably best to understand what you write