最大子数组问题(分治算法)--算法导论

代码(参考《算法导论》伪代码):

#include <iostream>
const int ∞ = -1000000;
int max_left=0;
int max_right=0;
using namespace std;
 
int FindMaxCrossSubarray(int A[], int low, int mid, int high)  
{
    int left_sum = ∞;
    int sum = 0;
	
    for (int i = mid; i >= low; i--) 
    {
        sum += A[i];
        if (sum >left_sum)
        {
            left_sum = sum;
            max_left = i;
        }
    }
 
    int right_sum = ∞;
    sum = 0;
    for (int i = mid + 1; i <= high; i++) 
    {
        sum += A[i];
        if (sum > right_sum)
        {
            right_sum = sum;
            max_right = i;
        }
    }
	return (max_left,max_right,left_sum + right_sum);
}
 
int FindMaxSubarray(int A[], int low, int high)
{
	int left_sum, right_sum, cross_sum,left_low,left_high,right_low,right_high,cross_low,cross_high;
    if (high == low)  //一个元素
    {
		return (low,high,A[low]);
    }
    else
    {
        int mid = (low + high) / 2; //分治
		(left_low,left_high,left_sum) = FindMaxSubarray(A, low, mid);  //前半部
        (right_low,right_high,right_sum) = FindMaxSubarray(A, mid + 1, high);  //后半部
		(cross_low,cross_high,cross_sum) = FindMaxCrossSubarray(A, low, mid, high);  //跨越前后
 
        if (left_sum >= right_sum && left_sum >= cross_sum)  
            return (left_low,left_high,left_sum);
 
        else if (right_sum >= left_sum && right_sum >= cross_sum)  
            return (right_low,right_high,right_sum);
 
        else  //跨越
            return (cross_low,cross_high,cross_sum);
    }
}
 
int main()
{
    int a[] = {10, -43, 25, 20, 3, -6, -13, 18, -20, 7, 10, -7, -2, 15, -41, 17};
   
    int length = sizeof(a) / sizeof(int);
    cout<<FindMaxSubarray(a, 0, length - 1)<<endl;
    cout<<"最大子序列的下标:"<<max_left<<"->"<<max_right<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值