Binary Search

Write your question here.
can anyone help me..i m facing a little problem while running this code...
the problem is that if i enter a number which is not present in the array it still shows that "the required value is at index 0)...
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
  Put the code you need help with here.


#include <iostream>
#include <conio.h>
using namespace std;

int binarySearch (int _array [],int _size,int key)
{
	int start = 0, end = _size-1;
	
	
	while (start <= end)
		{
			int mid = (start+end)/2;
			if ( key == _array [mid])
			return mid;
			if (key > _array [mid])
				{
					start = mid+1;
				}
			else 
				{
					end = mid-1;
				}
		}
	return 0;
}
	

void main ()
{
	const int arraySize = 10;
	int arr [arraySize] = {13,19,5,26,3,49,57,69,23,31};
	int _temp;
	int searchValue;
	int _index;
	for (int i=0;i<arraySize;i++)
		{
			for (int j=0;j<arraySize-1;j++)
				{
					if (arr [j] > arr [j+1])
						{
							_temp = arr [j];
							arr [j] = arr [j+1];
							arr [j+1] = _temp;
						}
				}
		}
	cout << "Sorted array is : \n";
	for (int k=0;k<arraySize;k++)
		{
			cout << arr [k] <<  "\t";
		}
	cout << "Enter the value you want to search : ";
	cin >> searchValue;
	_index = binarySearch ( arr,arraySize,searchValue);
	if (_index !=0 )
		cout << "The required value is at index : " <<_index;
	else
		cout << "The required value is not found. ";
	getch ();
}



Well, in the binarySearch function you put return 0; so... You can choose to return -1 if the element is not present in the array, or you can define a function like

 
bool binarySearch(int _array [],int _size,int key, int* position)


which returns true if the element is present or false otherwise. The last parameter is a pointer to an int, where you can store the position of the element (in case it is found).

The two strategies should lead to the same result, but the first one is maybe easier.
Last edited on
thank you very much....:)
Topic archived. No new replies allowed.