In: Computer Science
Please use C++ for Mac (XCode)
In this program, a user can search for a name within a list of names. Here are the steps the program will implement:
1. Reads the names from the file names.txt into a vector that stores strings.
2. Sorts the names in alphabetical order using selection sort.
3. The program then prompts the user to enter a name.
4. The program then uses binary search to see if the name is in the list.
5. If the name is in the list, the program prints: "The name you entered is in the list!"
6. If the name entered was not in the list, the program prints "The name you entered was not in the list."
Notes: You will need to change your swap function to swap strings, like this:
void swap(string& x, string& y)
{
string temp = x;
x = y;
y = temp;
}
SOLUTION-
I have solve the problem in C++ code with comments and screenshot
for easy understanding :)
CODE-
//c++ code
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;
//function to sort the vector of stirng usign selection sort
void selection_sort(vector<string> &names)
{
int n = names.size();
//iterate over the vector
for (int j = 0; j < n - 1; ++j)
{
int min = j;
//find the smallest
element
for (int i = j+1; i < n;
++i)
{
if (names.at(min) > names.at(i))
{
min = i;
}
}
//swap it with current
element
if (min != j)
swap(names.at(j),
names.at(min));
}
}
//function to swap two strings
void swap(string &x, string &y)
{
string temp = x;
x = y;
y = temp;
}
//function to search a string using binary search
bool binary_search(vector<string> names, string name)
{
int left = 0;
int right = names.size() - 1;
//iterate while left less than or equal to right
while(left <= right)
{
//find the mid
int mid = (left +
right)/2;
//if the name is equal to name
at mid index
if(names.at(mid) ==
name)
{
//string found
return
true;
}
//if the name at mid index
less than give name search in the right side of mid
else if(names.at(mid) <
name)
{
left =
mid + 1;
}
//otherwise search in the left
of the mid
else
{
right
= mid - 1;
}
}
//string not found
return false;
}
int main()
{
//open the file to read
ifstream infile ("names.txt");
vector<string> names;
string line;
//read the file line by line
while(getline(infile, line))
{
names.push_back(line);
}
//call the function to sort the names
selection_sort(names);
string name;
//prompt the user to enter a name
cout<<"Enter a name:\t";
cin>>name;
//search for the name using binary search
if(binary_search(names, name))
{
cout<<"The name you
entered is in the list"<<endl;
}
else
{
cout<<"The name you
entered is not in the list"<<endl;
}
}
names.txt contains
james
marry
smith
arena
bob
alice
john
danyi
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------