I was implementing Binary Search on arrays using recursion in C. However I keep getting erroneous index values for the search results. Please can anyone test run the code for different values and comment on how to fix the problem?
My code is as below:
#include<stdio.h>
#include<process.h>
int arr[100];
int retindex(int, int, int);
void main()
{
int i=0, num=0, digits=0, j=0, temp=0, element=0, beg=0, mid=0, last=0, index=0, flag=0;
printf("%s\n", "Please enter the numeric array (Enter 10101 to terminate) : ");
for(i=0; ; i++)
{
scanf("%d", &num);
if(num==10101)
break;
else
{
arr[i]=num;
++digits;
}
}
printf("\n\nSorting the numeric array...\nHence the entered numeric array is: \n\n");
for(i=0; i<(digits-1); i++)
{
for(j=(i+1); j<digits; j++)
{
if(arr[i]>arr[j])
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
for(i=0; i<digits; i++)
printf("%d\t", arr[i]);
printf("\n\nEnter the element you want to search for: ");
scanf("%d", &element);
printf("\n\nPerforming binary search...\n\n");
beg=0, last=digits, mid=(beg+last)/2;
index=retindex(element, beg, last);
if(index==-1)
printf("%s", "Element not found, exiting!");
else
printf("%s%d\n\n", "Hence the element being searched for lies at index number ", (index));
getch();
}
int retindex(int ele, int be, int la)
{
int mid;
mid=(be+la)/2;
if(ele<arr[mid])
retindex(ele, be, (mid-1));
else if(ele>arr[mid])
retindex(ele, (mid+1), la);
if(ele==arr[mid])
return mid;
}