时间复杂度为O(nlgn) typedef struct Array { int left; int right; int sum; }ARRAY,*ARRAYPOINT; //此函数类似于归并排序里的合并函数 ARRAY FIND_MAX_CROSSING_SUBARRAY(int *A,int low,int mid,int high) { ARRAY max; max.left=mid+1; max.right=mid; int left_sum=0; int sum=0; for(int i=mid;i>=low;--i) { sum+=A[i]; if(sum>left_sum||max.left>mid) { left_sum=sum; max.left=i; } } max.sum=sum; sum=0; int right_sum=0; for(int j=mid+1;j<=high;++j) { sum+=A[j]; if(sum>right_sum||max.right<mid+1) { right_sum=sum; max.right=j; } } max.sum+=sum; return max; } ARRAY FIND_MAXIMUM_SUBARRAY(int *A,int low,int high) { if(low==high) { ARRAY max; max.left=max.right=low; max.sum=A[low]; return max; } else { int mid=(low+high)/2; ARRAY left_max,right_max,cross_max; left_max=FIND_MAXIMUM_SUBARRAY(A,low,mid); right_max=FIND_MAXIMUM_SUBARRAY(A,mid+1,high); //类似于归并排序里的合并 cross_max=FIND_MAX_CROSSING_SUBARRAY(A,low,mid,high); if(left_max.sum>=right_max.sum&&left_max.sum>=cross_max.sum) return left_max; else if(right_max.sum>=left_max.sum&&right_max.sum>=cross_max.sum) return right_max; else return cross_max; } } int _tmain(int argc, _TCHAR* argv[]) { int A[]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22}; ARRAY max; max=FIND_MAXIMUM_SUBARRAY(A,0,sizeof(A)/sizeof(A[0])); printf("最大子数组从第%d个元素开始,到第%d个元素结束\n",max.left+1,max.right+1); printf("其和为:%d\n",max.sum); system("pause"); return 0; }