Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write and test a program that instantiates a function template that implement

ID: 3548487 • Letter: 1

Question

1. Write and test a program that instantiates a function template that implements a binary search of a sorted array of


objects.


Solution


#include <iostream>

#include <string>

using namespace std;

template<class T>

void binarysearch(T target, T ary[], int  start, int end)

{

            int middle = (start + end) / 2;

            int flag;

            if (ary[middle] == target)

            {

                        cout << "Taget " << target << " has been found at " << middle + 1 << " position" << endl;

                        flag = 1;

            }

            else

            if (target> ary[middle])

            {

                        binarysearch(target, ary, middle, end);

            }

            else

            if (target < ary[middle])

            {

                        binarysearch(target, ary, start, middle);

            }

}

int main()

{

            int i;

            int a[7] = { 3, 7, 9, 12, 19, 21 };

            cout << "INTEGER BINARY SEARCH" << endl << endl;

            cout << "Element in arry are: " << endl;

            for (i = 0; i<6; i++)

            {

                        cout << a[i] << " ";

            }

            cout << endl << endl << "Search for interger :" << endl;

            binarysearch(9, a, 0, 9);

            cout << endl << endl << "DOUBLE BINARY SEARCH" << endl << endl;

            double b[7] = { 3.500, 5.50000, 6.000000, 7.500000, 8.50000, 9.000000, 60.600000 };

            cout << "Element in arry are: " << endl;

            for (i = 0; i<6; i++)

            {

                        cout << b[i] << " ";

            }

            cout << endl << endl << "Test for target found: " << endl;

            binarysearch(7.5, b, 0, 6);

            //cout<<"============================================="<<endl<<endl;

            system("pause");

            return 0;

}



I need New and Different Source Code

Explanation / Answer

template <typename T, size_t Size>

int binarySearch(const Array<T,Size>&a, size_t first, size_t last, const T &x) {

if ((x < a.array[first]) || (x > a.array[last])) {

return -1;

}

if (a.array[first] == x) {

return first;

} else if (a.array[last] == x) {

return last;

}

int mid = (first+last)/2;

if (x > a.array[mid]) {

return binarySearch(a,mid+1,last,x);

} else {

return binarySearch(a,first,mid,x);

}

}


Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote