0

The program crashes in finding a number which is not available in the array.The code works perfectly when i search for elements which are available in the array.Help much appreciated.

#include<stdio.h>
int binarySearch(int a[],int s,int key)
{
    int middle;

    if(s!=1)
        middle=s/2;

    if(a[middle]==key)
        return 1;

    else if(key<a[middle])
        binarySearch(a,middle,key);

    else if(key>a[middle])
        binarySearch(&a[middle],middle,key);

    else
        return 0;
}

void main()
{
    int i;
    int a[]={1,2,3,4,6,9,10,11};

    for (i =0;i<8;i++)
        printf("%i ",a[i]);

    if(binarySearch(a,8,5))
        printf("\nFound");
    else
        printf("\nNot Found");
}
3
  • Try changing the base case to if(s<=1) return 0; Commented Feb 4, 2015 at 16:27
  • 1
    void main() is undefined behaviour. if s is equal to 1 you are using middle uninitialized. Commented Feb 4, 2015 at 16:27
  • 1
    There is bsearch() function in stdlib.h Commented Feb 4, 2015 at 16:28

4 Answers 4

1

Change

if(s!=1)
    middle=s/2;
if(a[middle]==key)
    return 1;
else if(key<a[middle])binarySearch(a,middle,key);
else if(key>a[middle])binarySearch(&a[middle],middle,key);

to

if (s != 1){
    middle = s / 2;
    if (a[middle] == key)
        return 1;
    else if (key<a[middle])binarySearch(a, middle, key);
    else if (key>a[middle])binarySearch(&a[middle], middle, key);
}

The variable middle is initialized only if s!=1.

I have run this code and got the value Not Found for input 5.

If you are running your code in release mode, try building it in debug mode and run step by step you will see what happens when middle is used directly without assigning it a specific value. This is harmful.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

The code if(key<a[middle])binarySearch(a,middle,key); does not return anything.

Try if(key<a[middle]) return binarySearch(a,middle,key);

This may still not work as you intend it to, but at least you will get past the major, immediately visible, cause of runaway recursion.

Comments

0

Because there is no case if the s == 1. "Middle" is not initialized and a[middle] is potential crash, or it will just go infinite.

Comments

0

A few notes:

Every branch of a recursive function should return something. You'll need to modify your recursive calls to return the call

Change

binarySearch(a, middle, key) 

to

return binarySearch(a, middle, key)

Also, make sure middle is computed properly. You don't properly initialize it in the situation where s == 1. You'll want this to start at 0 most likely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.