4月25日课上练习 一维数组最大子数组(debug版)

时间:2023-03-09 19:17:51
4月25日课上练习  一维数组最大子数组(debug版)

一维数组中求最大子数组的算法

package com.wangwang.mar;

import java.util.Scanner;
public class Sum { public static void main(String[] args) {
// TODO Auto-generated method stub Scanner sc=new Scanner(System.in);
System.out.println("输入数组长度");
int n=sc.nextInt();
System.out.println("输入数组数据(用空格分开)");
int i;
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt(); int begin=0;//子数组开始下标
int end=0;//子数组结束下标
int maxValue=a[0];
int tempValue=maxValue; //for循环寻找最大和的连续子数组
for(i=1;i<n;i++)
{
tempValue+=a[i]; if((tempValue>a[i])&&(tempValue>maxValue))
{
end=i;
maxValue=tempValue; } else if(tempValue<=a[i])
{
begin=i;
end=i;
tempValue=a[i]; }
} //输出最大和的连续子数组的相关信息
System.out.println("最大子数组和为:"+maxValue+"\n子数组内容为:");
System.out.println("下标:");
for(i=begin;i<=end;i++)
System.out.print(i+" ");
System.out.println("\n"+"下标对应数值:");
for(i=begin;i<=end;i++)
System.out.print(a[i]+" "); } }

 加入debug后,修改部分代码,如下:

 package com.wangwang.mar;

 import java.util.Scanner;
public class Sum { public static void main(String[] args) {
// TODO Auto-generated method stub Scanner sc=new Scanner(System.in);
System.out.println("输入数组长度");
int n=sc.nextInt();
System.out.println("输入数组数据(用空格分开)");
int i;
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt(); int begin=0;//子数组开始下标
int end=0;//子数组结束下标
int maxValue=a[0];
int tempValue=maxValue; System.out.println("设定起始数组为a[0]");
//for循环寻找最大和的连续子数组
for(i=1;i<n;i++)
{
tempValue+=a[i];
System.out.print("将a["+i+"]加入起始数组进行运算");
if(tempValue>a[i])
{
if(tempValue>maxValue) {
end=i;
maxValue=tempValue;
System.out.println(" "+"最大值更新,当前最大值为:"+maxValue);
}
else {
System.out.println(" "+"构成的新数组最大值不变为:"+maxValue);
}
} else if(tempValue<=a[i])
{
begin=i;
end=i;
tempValue=a[i];
maxValue=tempValue;
System.out.println(" "+"数组总和<该元素,该元素作为当前最大值为:"+maxValue);
}
} //输出最大和的连续子数组的相关信息
System.out.println("最大子数组和为:"+maxValue+"\n该子数组内容为:");
System.out.println("下标:");
for(i=begin;i<=end;i++)
System.out.print(i+" ");
System.out.println("\n"+"下标对应数值:");
for(i=begin;i<=end;i++)
System.out.print(a[i]+" "); } }

运行结果,如图:

4月25日课上练习  一维数组最大子数组(debug版)