Binary Search on String

Hello,

Can someone look at the below and give me some feedback? Point of the program is to sort a string of names and then return the position when its found. I cant seem to get it to return anything when searching.

#include <iostream>
#include <string>
using namespace std;

int binarySearch(string, int, string);
string sort_Array(string, int);

int main()
{
const int NUM_NAMES = 20;
string name;
string names[NUM_NAMES] = { "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" };

// Insert your code to complete this program

//Ask the user to select the name of employee they want to look for

// Variables
string employee;
int search;

// Sort array first
sort_Array(employee, NUM_NAMES);

// Prompt for user input to enter an employee name
cout << "Please enter an employee's name: ";
getline(cin, employee);

// Search for name
search = binarySearch(names, NUM_NAMES, employee);

if (search == -1)
cout << "That name does not exist." << endl;
else
{
cout << "That name is found at element " << search << endl;
}

system("PAUSE");

return 0;
}

string sort_Array(string employee[], int size)
{
int Scan, minIndex;
string minValue;

for (Scan = 0; Scan < (size - 1); Scan++)
{
minIndex = Scan;
minValue = employee[Scan];
for (int index = Scan + 1; index < size; index++)
{
if (employee[index] < minValue)
{
minValue = employee[index];
minIndex = index;
}
}
employee[minIndex] = employee[Scan];
employee[Scan] = minValue;
}
}

int binarySearch(string names[], int NUM_NAMES, string value)
{
int first = 0,
last = NUM_NAMES - 1,
middle,
position = -1;
bool found = false;

while (!found && first <= last)
{
middle = (first + last) / 2;
if (names[middle] == value)
{
found = true;
position = middle;
}
else if (names[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
Hi :D
Pls use code tags next time.

Since you are not returning anything from sort_Array change it's type to void.

Your function prototypes should look more like this:
1
2
int binarySearch(string[], int, string);
void sort_Array(string[], int);


In main function you should call sort_Array(names, NUM_NAMES); instead of sort_Array(employee, NUM_NAMES);
Topic archived. No new replies allowed.