I need help with a c++ program. thank you. Modify the sort function to handle an
ID: 3718326 • Letter: I
Question
I need help with a c++ program. thank you.
Modify the sort function to handle an array of strings. In the main function display the array, both before, and after, the sort. After the array has been sorted, use the bSearch function (modified) to search for a string that the user has entered. If found display the message "found" along with its offset, if not found then display the message "not found". Upload the source code (cpp file) through quizzes link on left hand side of the Blackboard course page. Note: Your program must be able to handle lowercase and uppercase strings. Use the following array string str "Mike", "bob", "Bill", "william", "George", "geoffyExplanation / Answer
#include <iostream>
#include <algorithm>
using namespace std;
int binarySearch(string name[], string key)
{
int n = sizeof(name)/sizeof(name[0]);
int first = 0,
last = n - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (name[middle].compare(key) == 0)
{
found = true;
position = middle;
}
else if (name[middle].compare(key) > 0)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
int main()
{
string str[] = {"Mike", "bob", "Bill", "william", "George", "geoff"};
int n = sizeof(str)/sizeof(str[0]);
for(int i = 0; i < n; ++i)
transform(str[i].begin(), str[i].end(), str[i].begin(), ::tolower);
cout << "Before Sorting: ";
for(int i = 0; i < n; ++i)
cout << str[i] << endl;
sort(str, str + n);
cout << " After Sorting: ";
for(int i = 0; i < n; ++i)
cout << str[i] << endl;
string name;
cout << " Enter name to search: ";
cin >> name;
if(binarySearch(str, name) == -1)
cout << "Name not found";
else
cout << "Name found.";
return 0;
}
**Comment for any further queries.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.