Hello, I need to demonstrate the binary search using recursion, and I've run into a little problem. In my example, if "key" was 1, 2, 3, or 6, then it would return true. Anything else would give me an error. Why is that? Here's my code:
// binary search.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
bool binarySearch(int[], int, int, int);
int _tmain(int argc, _TCHAR* argv[])
{
int col[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int input;
int x = 0;
do
{
cout << "The collection: " << endl;
for (int i = 0; i < 10; i++)
{
cout << col[i] << "\t";
if (i == 4)
cout << endl;
}
cout << endl << endl;
cout << "Enter a number to see if it is in the collection: " ;
cin >> input;
binarySearch(col, 0, 10, input);
if (binarySearch(col, 0, 10, input) == true)
cout << "This number is in the collection!" << endl;
else
cout << "This number is not in the collection!" << endl;
x++;
system("pause");
system("cls");
} while (x < 10);
system("pause");
return 0;
}
bool binarySearch(int col[], int start, int end, int key)
{
int mid = (end - start) / (2 + start);
if (col[mid] == key)
return true;
else if (col[mid] < key)
{
if (mid > end)
return false;
else
return binarySearch(col, mid + 1, end, key);
}
else
{
return binarySearch(col, start, mid, key);
}
}