35.3k views
3 votes
Write a program that sorts a vector of names alphabetically using the selection sort and then searches the vector for a specific name using binary search. To do that, you need to write three functions: 1. void selSort (vector & v): sorts the vector using selection sort 2. void display (const vector & v): displays the vector contents 3. int binSearch (const vector & v, string key): searches the vector for a key, returns the index of the key if found and -1 if the index is not found

User Mente
by
7.1k points

1 Answer

1 vote

Answer:

See Explaination

Step-by-step 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;

}

User Newb
by
7.1k points