himmi
himmi

Reputation: 19

recursive binary search in c

When I run this it always shows Number Not Found when the number is other than one i.e. it runs correctly for number 1.

I want to know what is the problem with this as according to me it runs all my test cases correctly.

int search(int *a,int start,int end,int num)
{
  int mid;
  mid=(start+end)/2;
  if(start==end)
  {
    if(num==a[start])
      printf("Number Found");
    else
      printf("Number Not Found");
  }
  else
  {
    if(num>a[mid])
      search(&a[mid+1],mid+1,end,num);
    else
      search(&a[start],start,mid,num);
  }
}

int main()
{
  int arr[10]={1,2,3,4,5,6,7,8,9,10};
  search(arr,0,9,10);
}

Upvotes: 1

Views: 157

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

You should not pass a different pointer to the array; instead you are already changing the end indices of the intervals you are interested in.

Upvotes: 2

Related Questions