Recursive Binary Search

So i'm trying to write this recursive binary search but I need to do it with 3 arguments within int binarySearch(int array[], int low, int high, int searchValue). I'm struggling on this part because I have no idea how to reduce it to 3 or what can I add into main to make it work with 4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 #include <iostream>
using namespace std;

int binarySearch(int array[], int low, int high, int searchValue)
{
	if (high <= 1)
	{
		int mid = 1 + (high - 1) / 2;

		if (array[mid] == searchValue)
		{
			return mid;
		}
		if (array[mid] > searchValue)
		{
			return binarySearch(array, low, mid - 1, searchValue);
		}
		return binarySearch(array, low, mid + 1, searchValue);
	}
	return -1;
}

int main() {

	int val, myNums[1000];  // Yuck--magic number!
	int pos, cnt = -1;

	cout << "Enter numbers from smallest to largest, 0 to stop\n";
	do {
		cin >> myNums[++cnt];
	} while (myNums[cnt] != 0);

	do {
		cout << "Enter number to search for: ";
		cin >> val;
		if (val != 0) {
			pos = binarySearch(myNums, cnt, val);
			cout << "binarySearch reported " << pos << endl;
		}
	} while (val != 0);

	return 0;
}
You should be able to make either of these signatures work:

1
2
int binarySearch(int* begin, int* end, int value);
int binarySearch(int* array, unsigned size, int value);



int array[] and int* array are identical in this context.

Consider that a portion of a larger array is just a smaller array with a (possibly) different starting address and (possibly) different ending address.
So I channged to this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 #include <iostream>
using namespace std;

int binarySearch(int array[], int size, int searchValue)
{
    cout << "BST with size = " << size << "[ ";
    for (int i = 0; i < size; ++i){
        cout << array[i] << " ";   
    }
    cout << " ]" << endl;
    
	if (size >= 1)
	{
		int mid = (size - 1) / 2;
        cout << "Mid " << mid << endl;
		if (array[mid] == searchValue)
		{
			return mid;
		}
		if (array[mid] > searchValue)
		{
			return binarySearch(array,  mid - 1, searchValue);
		}
		if (array[mid] < searchValue)
		{
		    return binarySearch(array+mid+1, size-(mid + 1), searchValue);
		}
	}
	return -1;
}

int main() {

	int val, myNums[1000];  // Yuck--magic number!
	int pos, cnt = -1;

	cout << "Enter numbers from smallest to largest, 0 to stop\n";
	do {
		cin >> myNums[++cnt];
	} while (myNums[cnt] != 0);

	do {
		cout << "Enter number to search for: ";
		cin >> val;
		if (val != 0) {
			pos = binarySearch(myNums, cnt, val);
			cout << "binarySearch reported " << pos << endl;
		}
	} while (val != 0);

	return 0;
}


but after testing the second position I get wrong answer.
Topic archived. No new replies allowed.