我已经实现了一个从值数组中找到最大子数组的解决方案。我可以在运行我的分而治之算法之前打印出完整的数组,但我似乎无法弄清楚如何在算法运行后打印子数组。
int newArray[] = {31, -41, 59, 26, -53, 58, 97, -93, -23, 84};
int arraySize = (sizeof(newArray)/sizeof(int));
printArray(newArray, 0, arraySize - 1);
int total = maxSubDiv(newArray, 0, arraySize - 1);
这是我的主要功能的一个片段。我正在使用 printArray 函数在找到最大子数组之前打印整个数组。maxSubDiv 函数如下:
int maxSubDiv(int * Array1, int left, int right)
{
if(left == right)
{
return Array1[1];
}
int middle = (left + right)/2;
return findMax(maxSubDiv(Array1, left, middle), maxSubDiv(Array1, middle + 1, right), leftRightCross(Array1, left, middle, right));
}
int leftRightCross(int * Array1, int left, int middle, int right)
{
int sum = 0;
int leftSum = INT_MIN;
for(int i = middle; i >= left; i--)
{
sum = sum + Array1[i];
if(sum > leftSum)
{
leftSum = sum;
}
}
sum = 0;
int rightSum = INT_MIN;
for(int i = middle + 1; i <= right; i++)
{
sum = sum + Array1[i];
if(sum > rightSum)
{
rightSum = sum;
}
}
sum = leftSum + rightSum;
return sum;
}
该算法似乎测试得很好,但我只是无法打印出包含最大子数组整数的子数组。任何帮助深表感谢!
struct tuple{
int begin;
int end;
int length;
};
int findMax(int left, int right, int cross)
{
int max;
if(left > right && left > cross)
{
max = left;
}
else if(right > left && right > cross)
{
max = right;
}
else
{
max = cross;
}
return(left, right, cross);
}