/* i have forgotten how to do the setw for the output
(ex. Find Holland, Beth: 5)...getting all of the numbers to line up. also, i need to know how to modify this program so it reads in 20 strings from a file. i want to name the file names.dat. */
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
void selectionSort ( char names[][17], int n );
int binarySearch ( char name[], char names[][17], int n );
char names[20][17]= { "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 main()
{
cout << "Unsorted:"<<endl;
for ( int i = 0; i < 20; i++ )
cout<< names <<'\n';
cout<<endl;
selectionSort ( names, 20 );
cout << "Sorted:"<<endl;
for ( int i = 0; i < 20; i++ )
cout << names << '\n';
cout << endl;
cout << "Find Allen, Jim: ";
cout << binarySearch ( "Allen, Jim", names, 20 ) << endl;
cout << "Find Wolfe, Bill: ";
cout << binarySearch ( "Wolfe, Bill", names, 20 ) << endl;
cout << "Find Jones, Kevin : ";
cout << binarySearch ( "Jones, Kevin", names, 20 ) << endl;
cout << "Find Holland, Beth: ";
cout << binarySearch ( "Holland, Beth", names, 20 ) << endl;
cout << "Find Ross, Paula: ";
cout << binarySearch ( "Ross, Paula", names, 20 ) << endl;
cin.get();
}
void selectionSort ( char names[][17], int n )
{
// Fix for last name sort
for ( int i = 0; i < n; i++ )
names[strcspn ( names, "," )] = '\0';
// Sort
for ( int i = 0; i < n - 1; i++ ) {
char save[17];
int min = i;
for (int j = i + 1; j < n; j++) {
if ( strcmp ( names[j], names[min] ) < 0 )
min = j;
}
memcpy ( save, names, 17 );
memcpy ( names, names[min], 17 );
memcpy ( names[min], save, 17 );
}
// Recover first names
for ( int i = 0; i < n; i++ )
names[strlen ( names )] = ',';
}
int binarySearch ( char name[], char names[][17], int n )
{
int low = 0, high = n - 1;
while ( low <= high ) {
int mid = ( low + high ) / 2;
if ( strcmp ( name, names[mid] ) < 0 )
high = mid - 1;
else if ( strcmp ( name, names[mid] ) > 0 )
low = mid + 1;
else
return mid;
}
return -1;
}