Question: Define a template function bsearch ( ) , which finds the target item in a sorted array of elements of any type using the binary

Define a template function bsearch(), which finds the target item in a sorted array of elements of any type using the binary search algorithm. The binary search divides the input array into two halves and compare the target with the mid-point. If the target is equal to the mid-point, then return the index of the mid-point. If the target is larger than the mid-point, divide the right half into two halves and repeat the search. If the target is smaller than the mid-point, divide the left half into two halves and repeat the search. If the target is not found in the array, return -1.
Give both the function declaration and definition for the template. The declaration of the integer version of the bsearch() is given as follows. The bsearch()function has four argument: the array, the beginning index of the array, the ending index, and the target item. It returns the index of the element if it is found in the array. If the target is not found, the function returns -1. Assume that the type has the operator==, operator<, and operator> overloaded.
int bsearch (int a[], int beg, int end, int target);
(Hint: it is best to write the definition of the integer version of bsearch() first then convert it to a template function.)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!