here is my code. I don't know why it always returns the value that i do not ask for.?? This code display the name I typed in if it is inside the array.
//this will sort strings using selection sort
#include <iostream>
using namespace std;
const int NUM_NAMES = 20, SIZE = 17;
//function prototype
void selectionSort( char array[][SIZE], int size );
int binarySearch( char array[][SIZE], int numelems, char value[SIZE] );
int main()
{
char names[NUM_NAMES][SIZE] = {
"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", };
int result;
char nameString[SIZE];
selectionSort( names, NUM_NAMES );
cout << "Enter name: ";
cin.getline( nameString, SIZE );
result = binarySearch( names, NUM_NAMES, nameString );
if( result == -1 )
cout << nameString << " is not in the list.\n";
else
cout << names[result] << " found.\n";
return 0;
}
/*displayStrings function
void displayStrings( char array[][SIZE], int size )
{
for( int index = 0; index < size; index++ )
cout << array[index] << endl;
}*/
//selectionSort function
void selectionSort( char array[][SIZE], int size )
{
int startScan, minIndex;
char minValue[SIZE];
for( startScan = 0; startScan < (size - 1); startScan++ )
{
minIndex = startScan;
strcpy( minValue, array[startScan] );
for( int index = startScan + 1; index < size; index++ )
{
if( strcmp( array[index], minValue ) < 0 ) {
strcpy( minValue, array[index] );
minIndex = index;
}
}
strcpy( array[minIndex], array[startScan] );
strcpy( array[startScan], minValue );
}
}
//The binarySearch function
int binarySearch( char array[][SIZE], int numElems, char value[SIZE] )
{
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;
}