FIND-MAX-CROSSING-SUBARRAY(A,low,mid,high) leftsum=-∞ sum = 0 for i = mid downto low sum = sum + A[i] if sum > leftsum leftsum = sum maxleft = i rightsum=-∞ sum = 0 for j = mid + 1 to high sum = sum + A[j] if sum > rightsum rightsum = sum maxright = j return (maxleft, maxright, leftsum + rightsum) FIND-MAXIMUM-SUBARRAY(A,low,high) if high == low return (low, high, A[low]) else mid = (low+high)/2 (leftlow ,lefthigh, leftsum) = FIND-MAXIMUM-SUBARRAY(A, low,mid) (rightlow ,righthigh, rightsum) = FIND-MAXIMUM-SUBARRAY(A, mid + 1, high) (crosslow ,crosshigh, crosssum) = FIND-MAX-CROSSING-SUBARRAY(A,low,mid,high) if leftsum>=rightsum and leftsum>=crosssum return (leftlow ,lefthigh, leftsum) elseif rightsum>=leftsum and rightsum>=crosssum return (rightlow ,righthigh, rightsum) else return (crosslow ,crosshigh, crosssum)Java代码:
public class FindMaxSubarray { public static int[] Find_Max_Crossing_Subarray(int[] a, int low, int mid, int high) { int leftsum = 0; int sum = 0; int maxleft = 0; for(int i = mid ; i > low; i--) { sum = sum + a[i]; if(sum > leftsum) { leftsum = sum; maxleft = i; } } int rightsum = 0; sum = 0; int maxright = 0; for(int j = mid + 1 ; j < high ; j++) { sum = sum + a[j]; if(sum > rightsum) { rightsum = sum; maxright = j; } } return new int[] {maxleft, maxright, leftsum + rightsum}; } public static int[] Find_Maximum_Subarray(int []a, int low, int high) { if(high == low) { return new int[] {low, high, a[low]}; } else { int mid = (low + high) / 2; int[] leftSubarray = Find_Maximum_Subarray(a, low, mid); int[] rightSubarray = Find_Maximum_Subarray(a, mid+1, high); int[] crossSubarray = Find_Max_Crossing_Subarray(a, low, mid, high); if(leftSubarray[2] >= rightSubarray[2] && leftSubarray[2] >= crossSubarray[2]) { return leftSubarray; } else if(rightSubarray[2] >= leftSubarray[2] && rightSubarray[2] >= crossSubarray[2]) { return rightSubarray; } else { return crossSubarray; } } } public static void main(String[]args) { int []a = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7}; int []result = Find_Maximum_Subarray(a, 0, a.length-1); System.out.print("最大子数组序列: "); for(int i = result[0]; i <= result[1] ; i++) { System.out.print(a[i]+" "); } System.out.println(); System.out.println("最大子数组和:"+result[2]); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)