/*could someone show me how to create a text file named names.dat with names in a directory with an executable file? i want this program to find a name after i enter it. here r the names that i want to put into names.dat.:*/
"Collins, Bill", "Smith, Bart", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
"Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
"Looney, Joe", "Wolfe, Bill", "James, Jean",
"Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
"Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth"
//here is the code for the program.:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int linear_search(string const array[], int amount, string const& name) {
for (int i = 0; i < amount; ++i)
if (array[i] == name)
return i + 1;
return 0;
}
void selection_sort(string array[], int amount) {
for (int i = 0; i < amount; ++i)
for (int j = i + 1; j < amount; ++j)
if (array[i] > array[j]) {
string tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
int binary_search(string array[], int amount, string const& name) {
int l = 0, r = amount - 1;
int comparisons = 0;
selection_sort(array, amount);
while (l <= r) {
++comparisons;
int m = (l + r) / 2;
if (name < array[m])
r = m - 1;
else if (name > array[m])
l = m + 1;
else
return comparisons;
}
return 0;
}
int main()
{
const int NUM_NAMES = 20;
string array[NUM_NAMES];
ifstream input("names.dat");
if (!input) {
cout << "Cannot open input file: names.dat\n";
return -1;
}
int amount = 0;
while (getline(input, array[amount]))
++amount;
string name;
cout << "Enter a name for searching: ";
getline(cin, name);
int comparisons;
cout << "Linear search: ";
if (comparisons = linear_search(array, amount, name))
cout << "Amount of comparisons: " << comparisons << "\n";
else
cout << "Not found\n";
cout << "Binary search: ";
if (comparisons = binary_search(array, amount, name))
cout << "Amount of comparisons: " << comparisons << "\n";
else
cout << "Not found\n";
return 0;
}
//thanks for the help.