算法导论第三章 最大子数组

#include<stdio.h>
struct CMaxSum
{
    int lowIndex;
    int highIndex;
    int maxSum;
};

/*******Brute force *********/
struct CMaxSum GetMaxSum(int *a,int n)
{
    int i,j,sum;
    struct CMaxSum maxSum={0,0,0};
    for(i=0;i<n;i++)
    {    
        sum=a[i];
        for(j=i+1;j<n;j++)
        {
            sum+=a[j];
            if(sum>=maxSum.maxSum)
            {
                maxSum.maxSum=sum;
                maxSum.lowIndex=i;
                maxSum.highIndex=j;
            }
        }
    }
    return maxSum;
}
/*******Brute force  end*********/


/*******Divide-And-Conquer strategy***********/
struct CMaxSum FindCrossSum(int *a,int low,int mid,int high)
{
    int sum1=0;
    int sum2=0;
    int tmp=0;
    int i;
    struct CMaxSum maxSum={0,0,0};
    for(i=mid;i>=low;i--)
    {
        tmp+=a[i];
        if(tmp>sum1)
        {
            sum1=tmp;
            maxSum.lowIndex=i;
        }
    }
    tmp=0;

    for(i=mid+1;i<=high;i++)
    {
        tmp+=a[i];
        if(tmp>sum2)
        {
            sum2=tmp;
            maxSum.highIndex=i;
        }
    }
    maxSum.maxSum=sum1+sum2;
    return maxSum;
}
struct CMaxSum FindSum(int *a,int low,int high)
{
    struct CMaxSum maxSum={0,0,0};
    if(low==high)
    {
        maxSum.highIndex=high;
        maxSum.lowIndex=low;
        maxSum.maxSum=a[low];
    }
    else
    {
        int mid=(high+low)/2;
        struct CMaxSum leftSum=FindSum(a,low,mid);
        struct CMaxSum rightSum=FindSum(a,mid+1,high);
        struct CMaxSum crossSum=FindCrossSum(a,low,mid,high);

        maxSum=(leftSum.maxSum>rightSum.maxSum?leftSum:rightSum);
        maxSum=(maxSum.maxSum>crossSum.maxSum?maxSum:crossSum);
        
    }
    return maxSum;
}

/*******Divide-And-Conquer strategy**********/

/******Line *************************/
struct CMaxSum LineSum(int *a,int n)
{
    int tmp=0;
    int i;
    struct CMaxSum maxSum={0,0,0};
    for(i=0;i<n;i++)
    {
        tmp+=a[i];
        if(maxSum.maxSum<tmp)
        {
            maxSum.maxSum=tmp;
            maxSum.highIndex=i;
        }
        if(tmp<0)
        {
            tmp=0;
            maxSum.lowIndex=i+1;
        }
    }
    return maxSum;
}
/******Line*************************/
int main()
{
    int a[]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
    struct CMaxSum maxSum;
    //maxSum=GetMaxSum(a,sizeof(a)/sizeof(int));
    //maxSum=FindSum(a,0,sizeof(a)/sizeof(int)-1);
    maxSum=LineSum(a,sizeof(a)/sizeof(int));
    printf("lowIndex=%d highIndex=%d sum=%d\n",maxSum.lowIndex,maxSum.highIndex,maxSum.maxSum);
}

猜你喜欢

转载自blog.csdn.net/limengjuhanxin/article/details/55007372