/**
* 最大子数组问题 采用分治策略
* @author wu
*
*/
public class FindMaxMumSubarray {

returnParameter rtP=new returnParameter();
returnParameter rtPleft=new returnParameter();
returnParameter rtPRight=new returnParameter();
returnParameter rtPCorss=new returnParameter();

public returnParameter FindMaxMumSubbarray1(int a[],int low,int high){
int mid;
if(low==high){//there is only one element in array a[]
rtP.sum=a[low];
rtP.low=low;
rtP.high=high;
rtP.print();
return rtP;

}
else{

mid=(low+high)/2;
System.out.println("(1)");
rtPleft= FindMaxMumSubbarray1(a, low, mid);
System.out.println("(2)");
rtPRight=FindMaxMumSubbarray1(a, mid+1, high);
System.out.println("(3)");
rtPCorss=FindMaxCorssingSubarray(a,low,mid,high);

if(rtPleft.sum>=rtPCorss.sum && rtPleft.sum>=rtPRight.sum){
rtPleft.print();
return rtPleft;
}

else if(rtPRight.sum>=rtPleft.sum && rtPRight.sum>=rtPCorss.sum){
rtPRight.print();
return rtPRight;
}

else{
rtPCorss.print();
return rtPCorss;
}
}


}


private returnParameter FindMaxCorssingSubarray(int[] a, int low, int mid, int high) {
returnParameter rtp=new returnParameter();
int max_left = 0,max_right = 0;
int left_sum=(int) -9.99e20;
int sum=0;
for(int i=mid;i>=low;i--){
sum+=a[i];
if(sum>left_sum){
left_sum=sum;
max_left=i;
}
}
int right_sum=(int) -9.99e20;
int sum1=0;
for(int j=mid+1;j<=high;j++){
sum1+=a[j];
if(sum1>right_sum){
right_sum=sum1;
max_right=j;
}
}
rtp.low=max_left;
rtp.high=max_right;
rtp.sum=left_sum+right_sum;
return rtp;

}
}

posted on 2014-03-20 19:33  pattywgm  阅读(259)  评论(0编辑  收藏  举报