0

In binary we have low and high values upon which we move either left or right. I'm solving questions on binary search and have a confusion on which value to return; low or high. For eg., to find the square root of a number using binary search when I returned low, the output was incorrect but when I returned high it passed all the cases. Similarly for this question, I returned the low and got the correct output. Is there any specific trick to decide what exactly to return?

Thanks in advance.

I couldn't really come up with a solution to this. Whenever I get wrong output, I switch the output between low and high and it works.

Jorn
  • 20,612
  • 18
  • 79
  • 126
Karthik
  • 31
  • 1
  • 1
  • 7
  • This doesn't seem to be about any language specifically, so I removed the specific language tags and added `language-agnostic`. – Jorn Jul 20 '23 at 08:48
  • 1
    There are several ways to implement binary search. It depends on things like: is `high` considered inclusive in the current range, or not? Does the loop check for equality to bail out sooner, or not? Just saying you sometimes return `low` or `high` doesn't give much of a clue of what you are actually doing. In some versions of the algorithm, `low` and `high` are equal at the end of the logic, so it wouldn't even matter. – trincot Jul 20 '23 at 09:40
  • I guess you are not going to enlighten us on the binary search algorithm you have used. Moving on. – trincot Jul 20 '23 at 10:41
  • The way I write it, `low == high` at the end, so it doesn't matter which one you return: https://stackoverflow.com/questions/38258457/where-is-the-mistake-in-my-code-to-perform-binary-search/38258974#38258974 – Matt Timmermans Jul 20 '23 at 11:44

0 Answers0