zoukankan      html  css  js  c++  java
  • 软件工程第三次作业

    求最大连续子数组和(最大子段和)

    算法设计

       一个数组arr,求它的最大连续子数组的和,使用currentSum来计算当前连续子数组的和,如果currentSum小于0,那么无论后面再加上什么数字都只会让子数组变小,所以抛弃当前子数组,重新开始计算子数组的值。算法流程图如图1。

    ![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416194345668-2050294096.png)
    **图1**
    ## 算法编码实现    [Coding 地址][1]

       算法实现如下:

    public class MaxSubArray {
    	// 求数组最大连续子数组的和
    	public static int getMaxSubArray(int[] arr) {
    		
    		int len = arr.length;// 数组大小
    		int maxSum = 0; // 记录子数组的和
    		int currentSum = 0; // 当前子数组的和
    		int low = 0; // 记录子数组的最低位下标
    		int height = 0; // 记录子数组的最高位下标
    		
    		for (int i = 0; i < len; i++) {
    			currentSum += arr[i];
    			if (currentSum > maxSum) {
    				maxSum = currentSum;
    				height = i;
    			} else if (currentSum <= 0) {
    				currentSum = 0;
    				low = i + 1;
    			}
    
    		}
    		
    		System.out.println("最大连续子数组下标" + low + "-" + height + " 最大连续子数组和:" + maxSum);
    		return maxSum;
    	}
    
    	
    }
    
    

    测试

    条件组合覆盖测试

       满足“条件组合覆盖”的测试用例是一定满足判定覆盖、条件覆盖、判定/条件覆盖的。由于我的代码每个if语句只有一个判断项,在设计测试用例的时候很容易达到条件组合覆盖。测试代码如下:

    	public class test {
    
    	@Test
    	public void testGetMaxSubArray1() {
    		int[] arr1 = {1, 4, -5, 9, 8, 3, -6};
    		assertEquals(20, MaxSubArray.getMaxSubArray(arr1));
    	}
    	@Test
    	public void testGetMaxSubArray2() {
    		int[] arr2 = {1, -2, 3, 10, -4, 7, 2, -5};
    		assertEquals(18, MaxSubArray.getMaxSubArray(arr2));
    	}
    
    }
    

       测试结果截图:

    ![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416201859811-408714918.png)
    **图2**
    ![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416201913980-1310051071.png)
    **图3**
  • 相关阅读:
    键盘事件
    冒泡事件-捕获事件-阻止事件
    Date()常用属性
    dom树节点的增删改插
    boost/c++11 变量类型打印、相等判断以及成员函数指针相关
    c++ std:call_once 与 单例模式实现
    c++11 异步编程 std::async
    c++ STL中一些常用函数/模板
    c++11 std::atomic 原子操作
    C++ std::atomic_flag 实现spinLock
  • 原文地址:https://www.cnblogs.com/jiaorenzhan/p/10719463.html
Copyright © 2011-2022 走看看