C++, sort names using linear and binary searches?

closed account (172v0pDG)
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <fstream>
#include <string>
using namespace 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;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}

Topic archived. No new replies allowed.