Exercise 5 (Binary Search). Let = [ao,1,...,n1] be an array of n integers. Assumc the array is sorted: ao a1...an-1.
1. Suppose the array has multiple occurrences of y. Which of the occurrences is returned by the following binary search implementation?
i static int search(int[] a, int y) { 2 int lo = 0, hi = a.length - 1; 3 while lo < hi { 4 int mid = lo + (hi - lo) / 2; 5 if (a[mid] <y) lo= mid + i; 6 else hi = mid; 7 8 return lo; 6
2. Suppose the array a has multiple occurrences of y. Which of the occurrences is returned by the following binary search implementation?
l static int search2(int[] a, int y) { 2 int lo = O, hi = a.length - 1; 3 while lo < hi) { 4 int mid = lo + (hi - lo) / 2; 5 if a[mid] > y) hi = mid; 6 else lo=mid + 1; 7 8 return hi - i; 9}
3. Give a simple logarithmic time algorithm, taking as input a sorted array of integers as well as some integer y, and which returns the number of occurrences of y in the array (and -1 if there are none).