What should a binary search function return if the target element is not found: -1 or an exception? Which is more appropriate?
Asked at
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.
Also asked at Astrum Entertainment
- What is the difference between the equality operator '==' and the strict equality operator '===' in PHP?
- How can you perform binary search on a sorted array of infinite or unknown length (when the count function is unavailable)?
- Why is rounding (floor) used when calculating the midpoint, what other ways are there to remove the fractional part in PHP, and which is more optimized (the difference between a function and a language construct)?
- Implement a weighted Round Robin algorithm (distributing requests across arrays according to their weights, for example 30%, 50%, 20%).
- Implement binary search on a sorted array.
Similar questions
- What will be the output when array_search() is used in an if condition?
- What is a B-tree?
- What is the time and space complexity of your implementation?
- What does empty() return for an empty string and zero?
- How can you make the second part of the previous problem produce 3, without using return or passing an object?