#include
#include
#include
#define SIZE 20
struct result find_max_crossing_subarray(const int *pt,int low,int mid,int high);
struct result find_max_subarray(const int *pt,int low,int high);
struct result
{ int index_start;
int index_end;
int sum;
};
int main(void)
{ //分配内存、生成随机数组、打印原始数组
int randnumber;
struct result result_;
int *pt=(int *)malloc(SIZE*sizeof(int));
if(!pt)
{ puts("Fail to allocate memory");
exit(EXIT_FAILURE);
}
puts("Rand Array");
for(int i=0;i
{ randnumber=rand()%SIZE-SIZE/2;
pt[i]=randnumber;
printf("%5d",pt[i]);
if((i+1)%10==0)
putchar('\n');
}
//计时
int time_start=time(0);
result_= find_max_subarray(pt,0,SIZE-1);
int time_end=time(0);
//打印最大子数组
printf("Consume:%ds\na Maximum Subarray include:\n",time_end-time_start);
for(int i=result_.index_start;i<=result_.index_end;i++)
{ printf("%4d ",pt[i]);
if(i%10==0)
putchar('\n');
}
putchar('\n');
printf("Max Value :%d",result_.sum);
free(pt);
}
struct result find_max_crossing_subarray(const int *pt,int low,int mid,int high)
{
int r_sum=-100;
int l_sum=-100;
int sum=0;
int max_l;
int max_r;
for(int i=mid;i>=low;i--)
{ sum+=pt[i];
if (sum>l_sum)
{ l_sum=sum;
max_l=i;
}
}
sum=0;
for (int i=mid+1;i<=high;i++)
{ sum=sum+pt[i];
if (sum>r_sum)
{ r_sum=sum;
max_r=i;
}
}
struct result result_={max_l,max_r,l_sum+r_sum};
return result_;
}
struct result find_max_subarray(const int *pt,int low,int high)
{
int mid;
if (high==low)
{ struct result result_={low,high,pt[low]};
return result_;
}
else
{ mid=(low+high)/2;
struct result result_=find_max_subarray(pt,low,mid);
struct result result__=find_max_subarray(pt,mid+1,high);
struct result result___=find_max_crossing_subarray(pt,low,mid,high);
if (result_.sum>=result__.sum && result_.sum>=result___.sum)
return result_;
else if(result__.sum>=result_.sum && result__.sum>=result___.sum)
return result__;
else
return result___;
}
}