您的位置:首页 > 其它

算法导论第三章

2017-09-16 12:48 134 查看

最大子数组

package com.gds.algorithms;

public class Tuple {
private int leftIndex;
private int rightIndex;
private int sum;

public Tuple(int leftIndex, int rightIndex, int sum) {
this.leftIndex = leftIndex;
this.rightIndex = rightIndex;
this.sum = sum;
}

/**
* @return the leftIndex
*/
public int getLeftIndex() {
return leftIndex;
}

/**
* @param leftIndex the leftIndex to set
*/
public void setLeftIndex(int leftIndex) {
this.leftIndex = leftIndex;
}

/**
* @return the rightIndex
*/
public int getRightIndex() {
return rightIndex;
}

/**
* @param rightIndex the rightIndex to set
*/
public void setRightIndex(int rightIndex) {
this.rightIndex = rightIndex;
}

/**
* @return the sum
*/
public int getSum() {
return sum;
}

/**
* @param sum the sum to set
*/
public void setSum(int sum) {
this.sum = sum;
}

}


package com.gds.algorithms;

public class FindSubarray {
public static Tuple findMaxCrossingSubarray(int[] A, int low, int mid, int high) {
int leftSum = Integer.MIN_VALUE;
int sum1 = 0;
int maxLeft = 0;
for (int i=mid; i >= low; i--) {
sum1 = sum1 + A[i];
if (sum1 > leftSum) {
leftSum = sum1;
maxLeft = i;
}
}

int rightSum = Integer.MIN_VALUE;
int sum2 = 0;
int maxRight = 0;
for (int j = mid+1; j <= high; j++) {
sum2 = sum2 + A[j];
if (sum2 > rightSum) {
rightSum = sum2;
maxRight = j;
}
}

Tuple t1 = new Tuple(maxLeft, maxRight, leftSum + rightSum);
return t1;

}

public static Tuple findMaximumSubarray(int[] A, int low, int high) {
Tuple t = null;
if (high == low) {
t = new Tuple(low, high, A[low]);
return t;
} else {
int mid = Math.floorDiv(low+high, 2);
int leftLow = findMaximumSubarray(A, low, mid).getLeftIndex();
int leftHigh = findMaximumSubarray(A, low, mid).getRightIndex();
int leftSum = findMaximumSubarray(A, low, mid).getSum();

int rightLow = findMaximumSubarray(A, mid+1, high).getLeftIndex();
int rightHigh = findMaximumSubarray(A, mid+1, high).getRightIndex();
int rightSum = findMaximumSubarray(A, mid+1, high).getSum();

int crossLow = findMaxCrossingSubarray(A, low, mid, high).getLeftIndex();
int crossHigh =findMaxCrossingSubarray(A, low, mid, high).getRightIndex();
int crossSum = findMaxCrossingSubarray(A, low, mid, high).getSum();

if (leftSum >= rightSum && leftSum >= crossSum) {
t = new Tuple(leftLow, leftHigh, leftSum);
return t;
} else if (rightSum >= leftSum && rightSum >= crossSum) {
t = new Tuple(rightLow, rightHigh, rightSum);
return t;
} else {
t = new Tuple(crossLow, crossHigh, crossSum);
return t;
}

}

}

public static void main(String[] args) {
int[] A = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
Tuple t = findMaximumSubarray(A, 0, A.length-1);
int low = t.getLeftIndex();
int high = t.getRightIndex();
int sum = t.getSum();
System.out.println("low: "+ low + "\n" + "high: " + high + "\n" + "sum: " + sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息