hhc wrote:
> I want to create a recursive function that uses the binary search
> algorithm. But every time I write the function into itself it doesn't
> work. The system compiles the program but it freezes before anything
> happens.If I take out the last line:<binsearch(val,array,high,low);>
> it doesn't crash.
> val is the value that we are searching for
> array is the array that we are searching in
> int binsearch(int val,int array[],int high,int low)
> {
> int mid;
>
> mid=(low+high)/2;
> if(val<array[mid])
> {high=mid-1;}
> else if(val>array[mid])
> {low=mid-1;}
> else
> {return(val);}
> binsearch(val,array,high,low);
> }
> I'm not sure if this is clear enough but just tell me any additional
> info you need.
This looks and sounds like homework, so my answer is intended to help
you find the answer for yourself.
If a recursive function 'freezes', it's probably failing to end the
recursion. Wait long enough and the freeze will probably stop, along with
a lot of (probably unhelpful) error messages.
Why not add something to help you understand what's going on ? If you
like using an interactive debugger, put a breakpoint on the entry
to that routine and see what's happening to its arguments.
Or if you don't like/have a debugger, put a call to printf at the beginning
of binsearch to tell you its arguments, or at least what 'high' and 'low' are.
Or walk through the code with these values:
Imagine that high=3 and low=1 on the first call to binsearch,
and that the value you seek is at array[3]. What value does mid
take ? What values are high and low set to before the first recursive
call to binsearch, if any ? And the next ? And the next ?
That way you may find enlightenment.
--
comp.lang.c.moderated - moderation address:
clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.