Answer:
See Explaination
Explanation:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
// Function Declarations
void display(vector<string> names);
void selectionSort(vector<string>& names);
int binarySearch(vector<string> names, string name);
int main()
{
string search;
vector<string> names{ "Joe Garcia", "Amelia Perez", "Bob Haynes", "Tim Ducrest", "Kevin Garcia", "Suzy Walter", "Fang Yi", "Robert James", "Mary Andres" };
cout << "__Displaying names before sort__" << endl;
display(names);
selectionSort(names);
cout << "__Displaying names after sort__" << endl;
display(names);
search = "Kevin Garcia";
int b1 = binarySearch(names, search);
if (b1 != -1) {
cout << search << " is found in the vector" << endl;
}
else {
cout << search << " is not found in the vector" << endl;
}
search = "Joe James";
b1 = binarySearch(names, search);
if (b1 != -1) {
cout << search << " is found in the vector" << endl;
}
else {
cout << search << " is not found in the vector" << endl;
}
return 0;
}
//This function will the Vector elements
void display(vector<string> names)
{
for (int i = 0; i < names.size(); i++) {
cout << names[i] << endl;
}
}
//This function will sort the Vector in ascending order
void selectionSort(vector<string>& names)
{
int start;
string temp;
for (int i = names.size() - 1; i > 0; --i) {
start = 0;
for (int j = 1; j <= i; ++j) {
if (names[j].compare(names[start]) > 0) {
start = j;
}
temp = names[start];
names[start] = names[i];
names[i] = temp;
}
}
}
//This function will search for a string in vector
int binarySearch(vector<string> names, string name)
{
int first = 0,
last = names.size() - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (names[middle] == name)
{
found = true;
position = middle;
}
else if (names[middle] > name)
last = middle - 1;
else
first = middle + 1;
}
return position;
}