简体   繁体   中英

Identifying the tail recursion call of this function

So I have a function that searchs for a certain number in an unordered array. I know that the last line of the function is the tail recursion call because is the last line. I know that in a tail recursion call the returns of the functions that this recursive call will call, are the same so that operations are all done before the recursion call.

But my question is, how can I know that this recursion call of my function ret = search_array (n , array , low , mid - 1) is not a tail recursion call?

I see easily other examples of tail recursion like the factorial number with an accumulator as a parameter but in this case I can not identify the tail recursion as easy as in other functions.

int search_array (int n , int * array , int low , int high ) {
    int mid , ret ;

    if ( low > high ) {
        return -1;
    }

    mid = ( low + high ) / 2;
    if ( array [ mid ] == n ) {
        return mid ;
    }

    ret = search_array (n , array , low , mid - 1) ;
    if ( ret != -1) {
       return ret ;
    }

    return search_array (n , array , mid + 1 , high ) ;
}

You say that

I know that in a tail recursion call [... the function's] operations are all done before the recursion call.

You apparently see that that is satisfied by

 return search_array (n , array , mid + 1 , high ) ;

Clearly, however, it is not satisfied by

 ret = search_array (n , array , low , mid - 1) ;

because the assignment to ret of the return value of the recursive call cannot be performed before the call is executed. That call is not tail recursive because the function must perform other operations after it returns. Even if the value returned were certain to be the recursive call's return value (which it is not), the central concept is not what the function returns, but rather whether it performs further operations between the recursive call and executing a return.

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