算法与数据结构-------递归查找最大元素

用两种递归方式查找数组中的最大元素。

方法1:

#include <stdio.h>
#include <stdlib.h>

int cmp1(int a[],int s,int e)
{
    int max1,max2;
    int m;
    int n = e - s + 1;
    m = s + n/2 - 1;
    
    if(n == 1)
    {
        return a[s];
    }
    else
    {
        max1 = cmp1(a,s+1,e);
        return max1 > a[s]? max1:a[s];
    }
}


方法2:
int cmp(int a[],int s,int e)
{    
    int max1,max2;
    int m;
    int n = e - s + 1;
    m = s + n/2 - 1;
    
    if(n == 1)
    {
        return a[s];
    }
    else
    {
        max1 = cmp(a,s,m);
        max2 = cmp(a,m+1,e);
        return max1 > max2? max1:max2;
    }
}


int main()
{

    int a[] = {3,1,4,5,0,10,3,2,4,6,7,8};
    int maxIndex = sizeof(a)/sizeof(int)-1;
    int max = cmp1(a,0,maxIndex);   //替换为cmp有同样效果。

    printf("max num %d\n",max);
    
}


两种方式的栈深度分别为n和log2N.

你可能感兴趣的:(数据结构,算法,递归,C语言,栈)