I can proudly say I developed this algorithm. But I certainly need to look at the hint of Programming Pearl Chapter 8 as well as the hint at 4-1.5. Though, make it working myself still makes me feel happy.
It is arguable that the algorithm could be too long so I might want to read other on-line references.
Should this be part of practice routine? It sounds like so. Though, it is more thought-provoking to finish exercises at the end of Programming Pearl Chapter 8.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define N 100
#define M 100000
struct arr_struct { int b; int e; int s; };
int main(int c, char* v[])
{
int A[N];
int i,k;
struct arr_struct max_array, max_suffix_array;
for(k=0;k<M;k++){
for(i=0;i<N;i++){
A[i]= 1 + (int ) (N * (float)rand()/(float)RAND_MAX) - N/2 ;
// printf("%d:%d ",i,A[i]);
}
// printf("\n");
max_array.s = A[0];
max_array.b = 0;
max_array.e = 0;
max_suffix_array.s = A[0];
max_suffix_array.b = 0;
max_suffix_array.e = 0;
for(i=1;i<N;i++){
if(max_suffix_array.s>0)
max_suffix_array.s+=A[i];
else{
max_suffix_array.s=A[i];
max_suffix_array.b=i;
}
max_suffix_array.e=i;
if(max_array.s < max_suffix_array.s){
max_array.s = max_suffix_array.s;
max_array.b = max_suffix_array.b;
max_array.e = max_suffix_array.e;
}
}
// printf("Begin %d\n",max_array.b);
// printf("End %d\n",max_array.e);
// printf("Sum %d\n",max_array.s);
}
return 0;
}
#include <stdlib.h>
#include <limits.h>
#define N 100
#define M 100000
struct arr_struct { int b; int e; int s; };
int main(int c, char* v[])
{
int A[N];
int i,k;
struct arr_struct max_array, max_suffix_array;
for(k=0;k<M;k++){
for(i=0;i<N;i++){
A[i]= 1 + (int ) (N * (float)rand()/(float)RAND_MAX) - N/2 ;
// printf("%d:%d ",i,A[i]);
}
// printf("\n");
max_array.s = A[0];
max_array.b = 0;
max_array.e = 0;
max_suffix_array.s = A[0];
max_suffix_array.b = 0;
max_suffix_array.e = 0;
for(i=1;i<N;i++){
if(max_suffix_array.s>0)
max_suffix_array.s+=A[i];
else{
max_suffix_array.s=A[i];
max_suffix_array.b=i;
}
max_suffix_array.e=i;
if(max_array.s < max_suffix_array.s){
max_array.s = max_suffix_array.s;
max_array.b = max_suffix_array.b;
max_array.e = max_suffix_array.e;
}
}
// printf("Begin %d\n",max_array.b);
// printf("End %d\n",max_array.e);
// printf("Sum %d\n",max_array.s);
}
return 0;
}