-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubArray_Violence.java
More file actions
47 lines (41 loc) · 1.3 KB
/
Copy pathMaxSubArray_Violence.java
File metadata and controls
47 lines (41 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package sort;
import java.awt.*;
import java.util.Arrays;
/**
* 习题4.1-2: 最大子数组暴力解法。Θ(n^2)
*
* @author 周何圳 2018年05月28日 新建
*/
public class MaxSubArray_Violence {
public MaxSubArrayBean findMaxSubArray(int[] src){
// 初始化最大子数组的返回值Bean
MaxSubArrayBean rest = new MaxSubArrayBean(-1,-1,-1);
// 数组校验
if(src.length < 2){
System.out.println("Error: Array length must be >= 2!");
return null;
}
int sum = Integer.MIN_VALUE,tempSum = 0;
for(int i = 0; i < src.length;i++){
for(int j = i; j< src.length; j++){
tempSum += src[j];
if(sum < tempSum){
sum = tempSum;
rest.startIndex = i;
rest.endIndex = j;
rest.sumValue = sum;
}
}
tempSum = 0;
}
System.out.println(rest);
return rest;
}
public static void main(String[] args) {
MaxSubArray_Violence m = new MaxSubArray_Violence();
for(int[] testData : TestData.MaxSubArrayTestData()){
System.out.println("Test: " + Arrays.toString(testData));
m.findMaxSubArray(testData);
}
}
}