返回一个整数数组中最大子数组的和(升级版)

设计思路

运用clock()函数来计算运行程序花了多少时间。运用宏定义来控制数组的长度。

源程序代码

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

#define N 10000

 

void main()

{

     clock_t start, finish;

     int a[N],b,c,d=0,i,j,k,t=-100,o=-100,x,y;

     double Time;

     cout<<"请输入数值范围:"<<endl;

     cin>>b>>c;

     cout<<"生成数组为:"<<endl;

     srand(unsigned(time(0)));

     for (i=0;i<N;i++)

     {

         a[i]=rand()%(c-b+1)+b;

         cout<<a[i]<<" ";

     }

     start = clock();

     for (i=0;i<N;i++)

     {

         for (j=i;j<N;j++)

         {

              d=0;

              for (k=i;k<=j;k++)

              {

                   d=d+a[k];

              }

              if (d>t) {t=d;x=i;y=j;}

         }

         if (t>o) o=t;

     }

     finish = clock();

     Time=finish-start;

     Time=Time/1000;

     cout<<endl<<"程序执行时间:(秒)"<<Time;

     cout<<endl<<"最大子数组的和:"<<endl;

     for (i=x;i<=y;i++)

     {

         if (a[i]>=0)

         {

              cout<<a[i];

         }

         else cout<<"("<<a[i]<<")";

         if (i!=y) cout<<"+";

         else cout<<"=";

     }

     cout<<o<<endl;

}

运行结果截图

下面我们来测试一下对于大型数组的工作效率

1000个数的数组程序执行时间0.058秒

2000个数的数组程序执行时间0.474秒

5000个数的数组程序执行时间6.956秒

8000个数的数组程序执行时间28.582秒

10000个数的数组程序执行时间55.213秒

测试结果

由于时间复杂度较高,10000个数的数组就有将近一分钟的等待时间,由此可见低时间复杂度的程序在处理大型数据时更加具有价值。

posted @ 2015-03-29 17:40  BUANG  阅读(201)  评论(0)    收藏  举报