Page 1 of 1

The following method is the non-recursive (iterative) implementation of binary search. Change the implementation of the

Posted: Thu Jul 14, 2022 2:12 pm
by answerhappygod
The Following Method Is The Non Recursive Iterative Implementation Of Binary Search Change The Implementation Of The 1
The Following Method Is The Non Recursive Iterative Implementation Of Binary Search Change The Implementation Of The 1 (122.64 KiB) Viewed 32 times
The following method is the non-recursive (iterative) implementation of binary search. Change the implementation of the following binary search operation so that if the array contains multiple occurrences of the target value, the method returns the index of first occurrence: public static int binarySearch (Comparable[] array, Comparable target)\{//returns the index of array that contains target or −1 if not found int first =0, last = array.length −1 while (first <= last) \{ int mid = first + (last − first) /2; int comp = target.compareTo(array[mid]); if (comp ==0 ) return mid; //successful search if (comp > 0) low = mid +1 else high = mid −1 \} return −1;// unsuccessful search 3 Ex: if array is [1,2,2,2,2,2,2,2,2,5,6,7] and target is 2, the method returns the index of the first occurrence of 2 which is 1.