ā Comprehension questions (LeetCode Binary Search)
Like the title says it's about this puzzle https://leetcode.com/problems/binary-search/description/
I am analysing a couple of solutions submitted on the site
One of the things that caught my attention is as follows: in an iterative solution there is no return statement in the if-block like this:
`
Any recursive solution I saw does return the recursion method however:
`
Could anyone kindly tell me why it is like this?
LeetCode
Binary Search - LeetCode
Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Ā
Example 1:
Input: num...
5 Replies
A recursive method has to use its own return value, so it has to return something
Ok I got it š
And why does an iterative method have to return nothing ?
You see, I have some gaps in understanding this š
Well, it might need to return something at the end
But it could also
Console.Write()
the result
Or use an out
parameter, or a ref
, or any number of other thingsit returns the value at the current index after the loop, supposedly
ah no, it returns in the loop
see the second statement in the loop
if it doesn't return, it loops again and again, until it does
if you returned later too, the loop would've been pointless
Ahh I got it! Thanks for the clarification @AntonC @Angius