I'm trying to get used to using the search functions, as their main focus is to just search for something specific in the array. I'm used to looking through numbers, since they only use int. But for this certain problem I'm trying to get, which states:
Create 2 search functions that search through an array of strings (read this from a file)
-A linear search
-A binary search
Pass an integer by reference which keeps track of how many comparisons each function performs for 3 runs each
-5 items
-10 items
-20 items
Resetting the value in between each set of calls
Print these numbers to the screen
I'm not sure basically how to search a text file, for in this case is a list of names, and to copy them into a array so the search functions can do their job. For the rest of the problem, I don't get what they're saying and would like context on what the book I'm learning this from can help me? Examples would be nice. This is the program so far.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int searchList(string [], int, string);
int main()
{
int SIZE1;
char names[20][20];
char temp[20];
int x = 0;
int results1;
string line;
ifstream myfile ("names.txt");
if (myfile.is_open())
{
int x=0;
while (myfile.good() )
{
for(int i = 0; i < 20; i++)
{
myfile.getline(temp,50);
strcpy_s(names[i],temp);
cout << line << endl;
}
}
myfile.close();
results1 = searchList(names, SIZE1, "Conrad");
}
system("pause");
return 0;
}
int searchList(string list[], int numElems, string value)
{
int index = 0;
int position = -1;
bool found = false;
while (index < numElems && !found)
{
if (list[index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
int binarySearch(int array[], int numElems, int value)
{
int first = 0,
last = numElems - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last)/2;
if (array[middle] == value)
{
found = true;
position = middle;
}
elseif (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}