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

Dani AI

Generated

As pointed out, the real bug is the midpoint expression on line 44. The code uses
mid = (end - start) / (2 + start), which does not compute the middle index between start and end. With the initial call (start = 0, end = 10) that expression evaluates to 5 (so col[5] == 6), then successive left-side recursions produce mid values 2, 1, 0 — which explains why 6, 3, 2 and 1 happen to be found while other values are missed or lead to incorrect indexing. The midpoint must be computed so the search range actually shrinks toward one end; otherwise recursion can be wrong or go out of bounds.

A safe, standard recursive implementation (using inclusive right bound) is:

bool binarySearchRecursive(const int a[], int left, int right, int key) {
    if (left > right)                       // empty range -> not found
        return false;
    int mid = left + (right - left) / 2;    // correct midpoint, avoids overflow
    if (a[mid] == key) return true;
    if (a[mid] < key)
        return binarySearchRecursive(a, mid + 1, right, key);
    return binarySearchRecursive(a, left, mid - 1, key);
}

Practical notes and debugging tips tied to the thread: call the function with the last valid index (for 10 elements, use right = 9) when using inclusive bounds; if preferring an exclusive upper bound use [left, right) conventions consistently and adjust recursion (recurse on [mid+1, right) or [left, mid)). Replace the incorrect if (mid > end) check with a proper base case (left > right). Also avoid calling the search twice from main (store the boolean result), and add small tests and prints of left, mid, right during development to verify the ranges shrink correctly. These fixes resolve the observed behavior reported by .

Recommended Answers

All 4 Replies

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.