Modify the binarySearch function presented in this chapter so it searches an arr
ID: 3532860 • Letter: M
Question
Modify the binarySearch function presented in this chapter so it searches an array of strings instead of an array of ints. Test the function with a driver program. Use Program 8-8 as a skeleton to complete. (The array must be sorted before the binary search will work.)
Program 8-8:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int NUM_NAMES = 20;
string names[NUM_NAMES] =
{"Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim",
"Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill",
"Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean",
"Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee",
"Harrison, Rose", "Setzer, Cathy", "Pike, Gordon", "Holland, Beth"};
// Insert your code to complete this program
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
const int NUM_NAMES = 20;
string names[NUM_NAMES] ={"Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim","Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill","Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean","Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee","Harrison, Rose", "Setzer, Cathy", "Pike, Gordon", "Holland, Beth"};
// Insert your code to complete this program
int i,j;
string temp;
for(i=0;i<NUM_NAMES-1;i++)
{
for(j=i+1;j<NUM_NAMES;j++)
{
if(names[i] > names[j])
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
string target,last,first;
printf("Enter the last name: ");
cin >> last;
printf("Enter the first name: ");
cin >> first;
target = last + ", " + first;
//cout << target << endl;
int low = 0, mid, high = NUM_NAMES-1;
while (low <= high)
{
mid = (low + high) / 2;
if (target < names[mid])
high = mid - 1;
else
{
if (target > names[mid])
low = mid + 1;
else
low = high + 1;
}
}
if (target == names[mid])
printf("Found ");
else
printf("Not found ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.