我做了最大的子數組算法,這似乎是錯誤的。由於C不能返回多個值,函數「maxarr」或「maxcarr」應該返回三個值 - (起始索引,結束索引和它的總和)在一個靜態結構「rettype」中。但是,那些返回值似乎是一樣的(我已經檢查過它的內存地址,它們都是一樣的)。我想這個錯誤發生的原因是靜態類型變量只聲明一次,不會被初始化多次,但我不知道如何糾正它。具有靜態結構返回類型的最大子數組
#include <stdio.h>
#include <stdlib.h>
struct rettype
{
int a;
int b;
int c;
};
struct rettype* maxarr(int i, int j, int* array);
struct rettype* maxcarr(int i, int j, int* array);
int main(void)
{
int array[20];
int temp = 0;
int num = 0;
int len = 0;
struct rettype* ret;
printf("Type length in.\n");
scanf("%d", &len);
while (num<len)
{
printf("%dth element: ", num);
scanf("%d", &array[num]);
num++;
}
ret = maxarr(1, len, array);
printf("Maximum Subarray:\nfrom element %d to element %d with sum of %d\n", ret->a, ret->b, ret->c);
return 0;
}
struct rettype* maxarr(int i, int j, int* array)
{
static struct rettype retb;
static struct rettype ret;
struct rettype* fretr;
struct rettype* fretc;
struct rettype* fretl;
int hi=j;
int mid;
int low=i;
mid = ((hi + low)/2);
if (i == j) {//base case
retb.a = i;
retb.b = j;
retb.c = *(array + i);
return &retb;
}
fretl = maxarr(i, mid, array);
fretr = maxarr(mid+1, j, array);
fretc = maxcarr(i, j, array);
if (fretl->c>fretr->c && fretl->c>fretc->c)
{
ret.a = fretl->a;
ret.b = fretl->b;
ret.c = fretl->c;
return &ret;
}
else if (fretr->c>fretl->c && fretr->c>fretc->c)
{
ret.a = fretr->a;
ret.b = fretr->b;
ret.c = fretr->c;
return &ret;
}
else
{
ret.a = fretc->a;
ret.b = fretc->b;
ret.c = fretc->c;
return &ret;
}
}
struct rettype* maxcarr(int i, int j, int* array)
{
int mid = (i + j)/2;
static struct rettype ret;
int a = mid;
int b = mid+1;
int risum = -9999;
int lesum = -9999;
int sum = 0;
while (a-->i)
{
sum += *(array + a);
if (sum>lesum)
{
lesum = sum;
}
}
sum = 0;
while (b++<j)
{
sum += *(array + b);
if (sum>risum)
{
risum = sum;
}
}
sum = 0;
ret.a = a;
ret.b = b;
ret.c = risum + lesum;
return &ret;
}
爲什麼要返回一個指針一個靜態的結構? C能夠很好地返回結構。 – mfro
'ret = maxarr(1,len,array);' - >'ret = maxarr(0,len-1,array);'? – BLUEPIXY