244 Intermediate C Programming
int main ( i n t argc , char * * argv )20
{21
int val = 4;22
int fv = func ( val );23
printf (" f(% d) = % dn " , val , fv ) ;24
return EXIT _SUCCES S ;25
}26
Some people mistakenly believe that recursion is slow. This is not true. The problem
is not recursion. The problem is redundant computation: func(2) is recomputed multiple
times. Recursion is fast when it is used correctly. Binary search and quick sort are two
examples. Some problems, such as integer partition, permutations, and combinations can
be solved naturally with recursion. Recursion is particularly helpful when the solution has
some symmetry with smaller solutions. This is indeed the case with all our recursive ex-
amples. Solving these types of problems using for or while loops is more difficult. In each
case working out the required number of iterations is non-obvious, and the implementation
details would be quite complicated. What makes recursion simple is that it is possible to
assume that the simpler cases are already solved. It is only necessary to figure out how to
express a solution in terms of smaller solutions, and then, so long as the base cases are
correct, the whole thing will work. This book puts great emphasis on recursion not because
recursion is always a good strategy, but because recursion is an excellent approach for solv-
ing certain classes of problems. Attempting to solve these problems with other techniques
can be difficult. If you understand recursion, then you can use it when recursion is a good
approach.
15.6 A Recursive Function with a Mistake
Consider the following incorrect implementation of binary search. One line in
binarysearch is incorrect, as marked by a comment. What is the output of this program?
// sear chbug . c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
int binary Search ( i n t * arr , in t key , i n t len ) ;4
#d ef in e ARRAYSIZ E 105
int main ( i n t argc , char * * argv )6
{7
int arr [ ARRAYS I ZE ] = {1 , 12 , 23 , 44 , 65 ,8
76 , 77 , 98 , 109 , 110};9
int ind ;10
for ( ind = 0; ind < ARRAYSIZE ; ind ++)11
{12
printf (" %d n" , b inarySe a rch ( arr , arr [ ind ],13
ARRAYSIZE )) ;14
}15
return EXIT _SUCCES S ;16
}17
18
int bina rySear chHel p ( in t * arr , i n t key , in t low , i n t high )19