C#C
C#3y ago
morry329#

✅ 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:
while(l<=r){
            int m=l+(r-l)/2;
            if(nums[m]==target)
                return m; //returns only here
            else if(nums[m]>target)
                r=m-1; //no return statement in this block
            else
                l=m+1; //here no return either. why??
        }
`
Any recursive solution I saw does return the recursion method however:
if (min > max)
        {
            return -1;
        }
        else
        {
            int mid = (min + max) / 2;
            if (target == inputArray[mid])
            {
                return mid;
            }
            else if (target < inputArray[mid])
            {
                return BinarySearchRecursive(inputArray, target, min, mid - 1); //returns the recursive method. why? 
            }
            else
            {
                return BinarySearchRecursive(inputArray, target, mid + 1, max); //here also. why?
            }
        }
`
Could anyone kindly tell me why it is like this?
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...
Was this page helpful?