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);
	}
}

Explain line 44.

Explain line 44.

I'm gonna be honest with you. My teacher gave the class part of this code, and said fix it. That's just what he had already written :p

I pointed you to the bug. It is at line 44. What is it supposed to do? What does it do?

I pointed you to the bug. It is at line 44. What is it supposed to do? What does it do?

It represents the middle of the array. It's used to separate the array into two parts so it can be searched easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.