public int binarySearchIter (int [] nums, int val)
{
int low = 0, high = nums.length-1;
while(high >= low)
{
int mid = (low+high)/2;
if(nums[mid] == val)
return mid;
else if(nums[mid] < val)
low = mid+1;
else
high = mid-1;
}
return -1;
}
1) What value is returned by the call binarySearch(values, target) as defined above? Trace the code to explain why.
2) How many times does the loop run if the target value is 10? Trace the code to explain why.�
// in a different class
int[] values = {1,3,5,7,8,8,8};
int target = 8;
Repl.it - Binary search: iterative implementation
During discussion, we saw that Toby and Andrew initially assigned high index as nums.length.
Does this work for all cases? If not, which cases will it not work and why?
Binary search: recursive implementation
Why do we need to add two more parameters in the method header?
public int binarySearch (int [] nums, int val, int low, int high)
{
// base case(s)
// recursive calls
}
Homework
Scanners last year?