i was looking for some D&C algorithms and came out founding this one
int sumArray(int anArray[], int size)
{
//base case
if (size == 0)
{
return 0;
}
else if (size == 1)
{
return anArray[0];
}
//divide and conquer
int mid = size / 2;
int rsize = size - mid;
int lsum = sumArray(anArray, mid);
int rsum = sumArray(anArray + mid, rsize);
return lsum + rsum;
}
but everytime i run the code without the base case it returns a segment fault error. im trying to figure out why this base case is so important that even running with n>1 it stills returning that error, someone would lend a hand here?
Because the function sumArray
calls itself recursively,
int lsum = sumArray(anArray, mid);
int rsum = sumArray(anArray + mid, rsize);
the base case is needed regardless of the size of the array. Otherwise Fnction can never exit the loop of calling itself!
And remember that base on the fact that one of mid
and rsize
could be odd or even both base cases for size == 0
and size == 1
:
if (size == 0)
{
return 0;
}
else if (size == 1)
{
return anArray[0];
}
are needed