简体   繁体   中英

Binary Search on Arrays using Recursion in C

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

Try this:

int retindex( int element, int lo, int hi )
{
    int mid = (lo+hi)/2;
    if( element < arr[mid] )
        return retindex( element, lo, (mid-1) );
    else if( element > arr[mid] )
        return retindex( element, (mid+1), hi );
    return mid;
}

Your function never returns the -1 that is looked for in main() . The best way I find to do a binary search, is to have the top index always out of range, ie it is never a candidate.

int retindex(int ele, int be, int la)
{
    int mid;
    mid = (be + la) / 2;
    if (mid == be) {
        if (ele == arr[mid])
            return mid;
        return -1;
    }
    if(ele < arr[mid])
        return retindex(ele, be, mid);
    if(ele > arr[mid])
        return retindex(ele, mid, la);
    return mid;
}
    return retindex(ele, be, (mid-1));

else if(ele>arr[mid])

    return retindex(ele, (mid+1), la);

Would be a good starting point.

When you have a recursive function whose return type is anything other than void , you have to make sure that you use the return value of the recursive call.

if(ele<arr[mid])
    retindex(ele, be, (mid-1));  // Missing return 
else if(ele>arr[mid])
    retindex(ele, (mid+1), la);  // Missing return

In your case, the function reaches the end of the function without executing a return when a recursive call is made. That leads to undefined behavior.

A programming suggestion -- minimize use of global variables in functions. retindex can easily be changed to accept the array as one of the arguments.

int retindex(int sorted_array[], int ele, int be, int la)
{
   int mid=(be+la)/2;
   if (mid == be) {
      if (ele == sorted_array[mid])
         return mid;
      return -1;
   }
   if(ele<sorted_array[mid])
      return retindex(sorted_array, ele, be, mid);
   else if(ele>sorted_array[mid])
      return retindex(sorted_array, ele, mid, la);
   else
      return mid;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM