Finding the maximum element of an array recursively

后端 未结 5 2060
遥遥无期
遥遥无期 2020-12-20 19:08

Consider this code, which computes the maximum element of an array.

#include 

int maximum(int arr[], int n)
{
    if (n == 1) {
        retur         


        
5条回答
  •  既然无缘
    2020-12-20 19:19

    Actually it is called only 4 times.

    The recursion rule, as you declared it is: if n==1, return ar[0] else return the maximum of n-1 elements.

    So, the else part is being called for 5, 4, 3 and 2.

    However, this recursion is not good enough. As your function is called n-1 times, you only pay the overhead of recursion (stack for example) but you get no advantage over iteration.

    If you really want recursion for this task, try to divide the array to 2 and pass each half to the recursive function.

    simple pseudo code (not handling odd numbers correctly):

    int max(int arr[], int n)
    {
        if (n<=1)
            return arr[0];
        return MAX(max(arr, n/2), max(arr+n/2, n/2));
    }
    

提交回复
热议问题