Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Exercise 14.1 In the previous lab, we used recursion in binary search. In order to carry out a binary search, the set must be sorted.

Exercise 14.1 In the previous lab, we used recursion in binary search. In order to carry out a binary search, the set must be sorted. Use the above program and the program given below (click here for the complete list) to write a new program that conducts a binary search in: 1) a set of values of type int, 2) a set of values of type float, 3) a set of values of type double, and 4) a set of values of type char.

Assume that the array may have up to 10 values.

Although, we have only listed four different cases, if the program is written using templates, it can be used for any variable type.

// Recursive program for binary search. #include using namespace std;

const int ARRAY_SIZE = 10;

void search(const int a[], int first, int last, int key, bool& found, int& location); int main( ) { int a[ARRAY_SIZE]; const int final_index = ARRAY_SIZE - 1; int i; for (i = 0; i < 10; i++) a[i] = 2*i;

int key, location; bool found; cout << "Enter number to be located: "; cin >> key; search(a, 0, final_index, key, found, location);

if (found) cout << key << " is in index location " << location << endl; else cout << key << " is not in the array." << endl;

return 0; }

void search(const int a[], int first, int last, int key, bool& found, int& location) { int mid; if (first > last) { found = false; } else { mid = (first + last)/2;

if (key == a[mid]) { found = true; location = mid; } else if (key < a[mid]) { search(a, first, mid - 1, key, found, location); } else if (key > a[mid]) { search(a, mid + 1, last, key, found, location); } } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Making Databases Work The Pragmatic Wisdom Of Michael Stonebraker

Authors: Michael L. Brodie

1st Edition

1947487167, 978-1947487161

More Books

Students also viewed these Databases questions