NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

What should a binary search function return if the target element is not found: -1 or an exception? Which is more appropriate?

Practice

AI answer

This is determined by the function's contract. For binary search, the usual return value is the index of the found element, or -1 if it is not found (as many standard APIs do, for example). In PHP, you can also return int|false or ?int if this is explicitly specified in the signature and documentation. An exception is usually unnecessary: an element not being found is a normal search result, not an error. Make sure not to use a value that could be a valid index.