I've written the following program to implement Binary Search of a sorted array:
int flag=0;
void binarysearch(int x, int a[], int m, int n)
{
int middle=(m+n)/2;
if(a[middle]==x)
{
printf("%d has been found at postion %d!\n", x, middle+1);
flag=1;
}
else
if(x > a[middle])
binarysearch(x, a, middle, n);
else
if(x < a[middle])
binarysearch(x, a, m, middle);
}
main()
{
int i, size, x;
int a[100];
printf("Enter the size of the list : ");
scanf("%d", &size);
printf("Enter the list items in ascending order : \n");
for (i=0; i<size; i++)
scanf("%d", &a[i]);
printf("Enter the element to be found : ");
scanf("%d", &x);
binarysearch(x, a, 0, size-1);
if(flag != 1)
printf("%d has not been found in the list!", x);
}
The problem with this program is, the function binarysearch recursively calls itself over and over again if an attempt is made to search an item that is not in the list. Therefore, the flag variable becomes completely pointless.
Is there a possibility of the program being able to tell the user if he is attempting to perform such a search (of something that's not in the array)?
I am assuming it is not possible as it is a basic flaw in the binary search algorithm. Please enlighten me.