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,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
andrsize
could be odd or even both base cases forsize == 0
andsize == 1
:are needed