int binarySearch(int nums[], int low, int high, int target) { if (low > high) return -1; int mid = (low + high)/2; if (target == nums[mid]) return mid; else if (target < nums[mid]) return binarySearch(nums, low, mid - 1, target); else return binarySearch(nums, mid + 1, high, target); } For the 4 statements below, indicate whether you think it is True or False. If you like, you can provide a description of your answer for partial credit in case you are incorrect. The code “if (low > high) return -1;” is a base case for this function The code “int mid = (low + high)/2;” is a base case for this function The code “if (target == nums[mid]) return mid;” is a base case for this function The code “else return binarySearch(nums, mid + 1, high, target);” is a base case for this function Code Analysis () If we change the first line of code in the function to be “if (low >= high) return -1;”, and we have an array defined as “int nums[] = {2, 3, 5, 7, 8, 10};”, answer the questions below if we called this function with “int index = binarySearch(nums, 0, nums.length - 1, 3);” For each iteration of binarySearch: What are the values of low, high, mid, and target variables? Will a base case be true? If so, what value is being returned If the base case(s) are false, which recursive function call will be made? After answering all the questions for each iteration, is the final value returned correct?
int binarySearch(int nums[], int low, int high, int target)
{
if (low > high)
return -1;
int mid = (low + high)/2;
if (target == nums[mid])
return mid;
else if (target < nums[mid])
return binarySearch(nums, low, mid - 1, target);
else
return binarySearch(nums, mid + 1, high, target);
}
For the 4 statements below, indicate whether you think it is True or False. If you like, you can provide a description of your answer for partial credit in case you are incorrect.
- The code “if (low > high) return -1;” is a base case for this function
- The code “int mid = (low + high)/2;” is a base case for this function
- The code “if (target == nums[mid]) return mid;” is a base case for this function
- The code “else return binarySearch(nums, mid + 1, high, target);” is a base case for this function
Code Analysis ()
If we change the first line of code in the function to be “if (low >= high) return -1;”, and we have an array defined as “int nums[] = {2, 3, 5, 7, 8, 10};”, answer the questions below if we called this function with “int index = binarySearch(nums, 0, nums.length - 1, 3);”
For each iteration of binarySearch:
- What are the values of low, high, mid, and target variables?
- Will a base case be true? If so, what value is being returned
- If the base case(s) are false, which recursive function call will be made?
After answering all the questions for each iteration, is the final value returned correct?
Trending now
This is a popular solution!
Step by step
Solved in 2 steps