/* The problem is solving the maximum subarray problem The complexity of the common method is n^2 now try to give a less than n ^2 algorithm Of course there must be negative numbers in the array, otherwise there is no meaning the use of divide-and-conquer strategy in this example */#include <stdio.h># include<stdlib.h>//defines the return structure of the body typedef struct result{ int left; // Left index int right; //right index int sum; //Max and}*res;// Solves the largest subarray containing intermediate values, with a complexity of Nres findmaxcrossingsubarray (Int *a,int left,int mid,int right) { res r=malloc (sizeof (Struct result)); int leftsum =* (A+mid); int sum=0; int i; Int maxleftindex=mid; for (i=mid;i>=left;i--) { sum+=* (a+i); if (Sum>leftSum) { leftsum=sum; maxLeftIndex=i; } } int rightsum=* (a+mid+1); sum=0; int j; int maxrightindex=mid+1; for (j=mid+1;j <=right;j++) { sum+=* (A+j); if (sum>rightsum) { rightsum=sum; maxrightindex =j; } } r-> Left=maxleftindex; r->right=maxrightindex; r->sum= (LeftSum +rightsum); return r;} Next, we use the divide-and-conquer method to find the maximum subarray of an array, with the assumption that there are negative elements, otherwise meaningless res findmaxsubarray (Int *a,int low,int high) { if (High==low) { res res= malloc (sizeof (struct result)); res->left=low; res->right=high; res->sum=* (a+low); return res; } else { int mid= (Low+high)/2; res resleft=findmaxsubarray (A,low,mid); res resright=findmaxsubarray (A,mid+1,high); res rescross=findmaxcrossingsubarray (A,low,mid,high); &nbSp; if (resleft->sum) >= (resright->sum) && (resleft->sum) >= (rescross->sum)) return resleft; else if (resright->sum) >= (resleft->sum) && (resright->sum) >= (rescross->sum)) return resRight; else return rescross; }}//Main test Program Void main () { int a[8]={ 5,-1,4,5,-2,3,-1,2}; res res=findmaxsubarray (a,0,7); printf ("%d\n", Res->sum);}
Solving maximal sub-array problem by divide-and-conquer method