# 最大子数组-分治策略-java

public class 最大子数组 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int []a = {2,2,-5,-6,-7,-8,-9};
int []max = new int[3];

max =sort(a);
System.out.println("左边界为：" +max[0]);
System.out.println("右边界为：" +max[1]);
System.out.println("最大子数组为： " +max[2]);

}

private static int[] sort(int[] a) {
// TODO Auto-generated method stub
int low = 0;
int high = a.length - 1;
int []max = new int[3];
max = find_maximum_subarray(a,low,high);
return max;
}

private static int[] find_maximum_subarray(int[] a, int low, int high) {
// TODO Auto-generated method stub
int []max = new int[3];
if(high == low){//数组内元素只有一个
max[0] = low;
max[1] = high;
max[2] = a[low];
return max;
}else{
int mid;
mid = (low+high)/2;
int []L = new int[3];
int []R = new int[3];
int []M = new int[3];
L = find_maximum_subarray(a,low,mid);
R = find_maximum_subarray(a,mid + 1,high);
M = find_max_crossing_subarray(a,low,mid,high);
if(L[2]>=R[2]&&L[2]>=M[2]){
return L;
}else if(R[2]>=L[2]&&R[2]>=M[2]){
return R;
}else {
return M;
}
}
}

private static int[] find_max_crossing_subarray(int[] a, int low, int mid, int high) {
// TODO Auto-generated method stub
int sum = 0;
int left_sum = 0;
int j = 0;
int left_line = 0;
for(int i = mid;i>=low;i--){
sum = sum +a[i];
if(j== 0){
left_sum = sum;
left_line = i;
j+=1;
}else if(sum > left_sum){
left_sum = sum;
left_line = i;
}
}
j = 0;
int right_line = 0;
int right_sum = 0;
sum = 0;
for(int i = mid + 1;i<=high;i++){
sum = sum +a[i];
if(j== 0){
right_sum = sum;
right_line = i;
j+=1;
}else if(sum > right_sum){
right_sum = sum;
right_line = i;
}
}
int []max = new int[3];
max[0] = left_line;
max[1] = right_line;
max[2] = left_sum + right_sum;

return max;

}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120