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 81 82 83 84 85 86
|
// Binary String Search.
// This program uses the data from BE0804 to conduct a binary search.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
const int M = 17;
char names[20][M] = {"Collins, Bill",
"Smith, Bart",
"Allen, Jim",
"Griffin, Jim",
"Stamey, Marty",
"Rose, Gerti",
"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"};
int n1, n2, pos;
char NameHolder[M], UserEntry[M];
int first = 0, last = M, middle;
bool found = false, stop = false;
int enter[M];
for (n1 = 0; n1 < M-1; n1++){
strcpy(NameHolder, names[n1]);
pos = n1;
for (n2 = n1 + 1; n2 < M; n2++){
if (int(names[n2][0]) < int(NameHolder[0])){
strcpy(NameHolder, names[n2]);
pos = n2;
}
}
strcpy(names[pos], names[n1]);
strcpy(names[n1], NameHolder);
}
cout << "Alphabetical names." << endl << endl;
for (n1 = 0; n1 < M; n1++){
cout << names[n1] << endl;
}
cout << "Enter a name to search for. The form must be Last, First." << endl;
cin >> UserEntry;
cout << endl;
while (!found && first <= last){ // While found is false and first is less than last
middle = (first + last) / 2; // middle is set to a value between first and last
if (UserEntry == names[middle]){ // if UserEntry is the selected middle name of the list
found = true; // then found is true. This should break the while.
}
else{ // Otherwise if UserEntry is not the selected middle name...
for (n1 = 0; stop == false; n1++){ // Enter a new loop that sets n1 = 0 and repeats until stop = true. n1++ every iteration.
middle = (first + last) / 2; // For the sake of the new loop, middle is set again to be between first and last.
if (int(names[middle][n1]) < int(UserEntry[n1])){ // If the int value of the n1'th letter,
// starting with 0 is less than the int value of UserEntry[n1]
first = middle + 1; // The first name in the search range becomes the name one above middle.
stop = true; // and the stop flag is set to true, thus breaking the for loop.
}
if (int(names[middle][n1]) > int(UserEntry[n1])){ // If the same condition is instead greater than
last = middle - 1; // The last name in the search range becomes the name one below middle.
stop = true; // and the stop flag is set to true.
} // If neither condition is true, it must be assumed that:
// 1. the user entry does not match the middle selection,
// and 2. the n1'th letters of both do match, thus the loop
// just needs to move on to n1++.
}
}
}
if (found == true)
cout << "That name exists." << endl;
else
cout << "Invalid entry." << endl;
}
|