The maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers (con Taining at least one positive number) which has the largest sum. For example, for the sequence of values 2, 1,? 3, 4,? 1, 2, 1,? 5, 4; The contiguous subarray with the largest sum are 4,? 1, 2, 1, with Sum 6. --from Wiki
Here we analyze the time performance of four algorithms, because the time difference is large, we divided into two groups for comparison:
Environment: Ubuntu 12.04
Time Unit: MS
Time performance: Presume that the input is Preread
Group One: number of input data elements 2000
/************************************************************************* > File name:algorithm1.c > Author:simba > Mail:dameng34@163.com > Created time:2012 year December 24 Monday 22:41 56 sec ************************* /#include <stdio.h> #include <stdlib.h> #include <
time.h> #include <sys/time.h> int maxsubsum1 (const int a[], int n) {int thissum, maxsum, I, J, K;
maxsum = 0;
for (i = 0; i < n; i++) {for (j = i; J < N; j +) {thissum = 0;
for (k = i; k <= J; k++) Thissum + = A[k];
if (Thissum > maxsum) maxsum = thissum;
} return maxsum;
int maxsubsum2 (const int a[], int n) {int thissum, maxsum, I, J;
maxsum = 0;
for (i = 0; i < n; i++) {thissum = 0;
for (j = i; J < N; j + +) {Thissum + = A[j];
if (Thissum > maxsum) maxsum = thissum;
} return maxsum;
Long GetTickCount (void) {struct Timeval TV;
Gettimeofday (&TV, NULL);
Return (TV.TV_SEC * 1000 + tv.tv_usec/1000);
int main (void) {int I, n = 2000;
int *ptr = malloc (sizeof (int) * n);
Srand (Time (NULL));
for (i = 0; i < n; i++) Ptr[i] = rand ()% 50-25;
Adopt algorithm 1 unsigned int utimecost = GetTickCount ();
int result = MAXSUBSUM1 (PTR, n);
Utimecost = GetTickCount ()-utimecost;
printf ("Max subsequence sum is%d, time cost%d\n", result, utimecost);
Adopt algorithm 2 Utimecost = GetTickCount ();
result = Maxsubsum2 (PTR, n);
Utimecost = GetTickCount ()-utimecost;
printf ("Max subsequence sum is%d, time cost%d\n", result, utimecost);
Free (PTR);
return 0; }