我正在尝试使用分而治之技术来实现在数组中查找最大子阵列总和的算法,但由于某种原因,程序没有终止,我无法自己成功调试它。有人能告诉我问题在哪里吗?
#include <iostream>
#include <cmath>
using namespace std;
int max_sub_arr(int arr[], int beginning, int end);
int helper_sub_arr(int arr[], int left, int center, int right);
int a[15] = {5, -2, 5, -6, 8, 20, -15, 4, 5, 3, -1, -2 , -5, 10, 1};
int length = 15;
int main()
{
cout <<max_sub_arr(a, 0, length-1) << endl;
return 0;
}
int max_sub_arr(int arr[], int beginning, int end)
{
if(beginning == end) return arr[beginning];
int center = (end - beginning)/2;
int left = max_sub_arr(arr, beginning, center);
int right = max_sub_arr(arr, center+1,end);
int cross = helper_sub_arr(arr, left, center, right);
if(left >= right && left >= cross) return left;
else if(right >= left && right >= cross) return right;
else return cross;
}
int helper_sub_arr(int arr[], int left, int center, int right)
{
cout<<"as";
int leftsum = -pow(2, 31);
int rightsum = -pow(2, 31);
int sum = 0;
int maxleft, maxright;
for(int i = center; i >= 0; --i)
{
sum += arr[i];
if(sum > leftsum)
{
leftsum = sum;
maxleft = i;
}
}
sum = 0;
for(int i = center + 1; i <= right; ++i)
{
sum += arr[i];
if(sum > rightsum)
{
sum = rightsum;
maxright = i;
}
}
return maxleft + maxright;
}
答案 0 :(得分:1)
将int center = (end - beginning)/2;
更改为int center = (end + beginning)/2;
运行后,我在50行得到分段错误,因为right
变量的值为72564.
请阅读http://www.geeksforgeeks.org/divide-and-conquer-maximum-sum-subarray/。