Hi everyone
I'm trying to do a binary search. My program compiles and links but when I come to execute it, when I enter a searchKey, nothing happens, presumably because my arguments aren't being passed to my function. What do I need to change please?
Here's my code:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int BinSearch(int data[], int numElements, int searchKey);
int main()
{
int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79 ,89 ,95};
int numElements = 23;
cout << "(";
for(int i = 0; i < 22; ++i)
{
if(i == 21)
{
cout << data ;
}
else
{
cout << data << ",";
}
}
cout << ")" << endl << endl;
string input = "0";
while (true)
{
cout << "Enter search key (or 'x' to exit): ";
cin >> input;
cout << endl;
if( input == "x" )
{
cout << "Exiting..." << endl;
break;
}
else
{
int n = atoi(input.c_str());
int searchKey = n;
cout << searchKey << " is in position " << BinSearch(data, numElements, searchKey);
}
}
}
int BinSearch(int data[], int numElements, int searchKey)
{
int first = 1;
int last = numElements;
int mid = (numElements + first) / 2;
bool quit = false;
while( !quit )
{
if( searchKey == data[mid] )
{
return mid;
quit = true;
}
else if( searchKey < data[mid] )
{
last = mid - 1;
}
else
{
first = mid + 1;
}
}
}
I also get the following warning:
------ Build started: Project: 3.7.7, Configuration: Debug Win32 ------
Compiling...
main.cpp
c:\documents and settings\chris moore\my documents\visual studio 2005\projects\3.7.7\3.7.7\main.cpp(75) : warning C4715: 'BinSearch' : not all control paths return a value
Build log was saved at "file://c:\Documents and Settings\Chris Moore\My Documents\Visual Studio 2005\Projects\3.7.7\3.7.7\Debug\BuildLog.htm"
3.7.7 - 0 error(s), 1 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
I think this is to do with the fact that I haven't specified what to do if the user enters a number that's not in the list. If this is the case, I won't worry about this for now, I just want to get it working for when the user quits or enters a number that is in the list.
Thanks,
Chris.