Hey guyz....
I was working on this assignment question:
Modify the binarySearch function given below so that it searches for a given name rather than an int. The functions returns and int which is the index of the name found. If -1 is returned then say name is not found otherwise write out the name and the mark for that name.
Code:
int binarySearch(int array[], int size, int value)
{
int first = 0, // First array element
last = size - 1, // Last array element
middle, // Mid point of search
position = -1; // Position of search value
bool found = false; // Flag
while (!found && first <= last)
{
middle = (first + last) / 2; // Calculate mid point
if (array[middle] == value) // If value is found at mid
{
found = true;
position = middle;
}
else if (array[middle] > value) // If value is in lower half
last = middle - 1;
else
first = middle + 1; // If value is in upper half
}
return position;
The array this function has is actually a text file with a list of names of students with their marks.
this is wat i have done so far:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int numElems = 20;
int binarySearch(string[], int, string);
int main ()
{
string first_name[20];
string lname[20];
string names[20];
int marks[20];
ifstream in_file;
in_file.open("TextFile3.txt");
for(int i=0; i<numElems; i++)
{
in_file>>lname[i]>>first_name[i]>>marks[i];
}
for(int i=0; i<numElems; i++)
{
names[i] = lname[i] + " " + first_name[i];
}
string value, fname, last_name;
cout<<"Please enter the name you would like to find: "<<endl;
cin>>last_name>>fname;
value = last_name + " " + fname;
int result = binarySearch(names, numElems, value);
if (result==-1)
{
cout <<"Can not find the name!"<<endl;
}
else
cout<<names[result]<<" "<<marks[result];
return 0;
}
int binarySearch(string list[], int numElems, string value)
{
int first = 0, // First list element
last = numElems - 1, // Last list element
middle, // Mid point of search
position = -1; // Position of search value
bool found = false; // Flag
while (!found && first <= last)
{
middle = (first + last) / 2; // Calculate mid point
if (list[middle] == value) // If value is found at mid
{
found = true;
position = middle;
}
else if (list[middle] > value) // If value is in lower half
last = middle - 1;
else
first = middle + 1; // If value is in upper half
}
return position;
}
when i run this program....it doesnt give me any errors....but every time i run it, first it asks me for a name...once i enter the name in, it says it cant find the name.......it only works for a couple of names which are Collins Bill and Looney Joe........plz help me!
This is the text file i used in this program:
Collins Bill 80
Smith Bart 75
Allen Jim 82
Griffin Jim 55
Stamey Marty 90
Rose Geri 78
Taylor Terri 56
Johnson Jill 77
Allison Jeff 45
Looney Joe 89
Wolfe Bill 63
James Jean 72
Weaver Jim 77
Pore Bob 91
Rutherford Greg 42
Javens Renee 74
Harrison Rose 58
Setzer Cathy 93
Pike Gordon 48
Holland Beth 79