### Divide n conquer algo

I am using a divide and conquer method to divide an array till it contains only 4 elements or less , once it contain 4 elements we need to sum the elements which is done by the func sum.
below is my code for divide.
when i run the program,the if condition is always satisfied and it does the sum of first 4 elements and the rest of the elements the else if condition is not satisfied, please let me know the error.

void divide(int a[], int start, int i, int l)
{

cout<<"Enter Divide";
int q = (i + start)/2;
cout<<q<<endl;
l++;
if (q = 4)
{
cout<<"Enter Sum";
sum(a,start,(q-1),l);
sum(a,q,i,l);
return;
}
else if (q>4)
{
cout<<"Enter else";
divide(a,start,q,l);
divide(a,q,i,l);
}
}
void sum (int a[],int ii, int jj, int l)
{
cout<<"Enter sum 2";
cout<<"The recurrence level is:"<<l<<endl;
for( counter = ii ;counter <= jj; counter ++)
{
}
cout<<"The sum of the elements of the subproblem is :"<<add<<endl;
}
 ``12`` ``````q = 4; //assignment q == 4; //comparison ``````
Please let me know the limiting condition coz it is goin into an infinite loop.
 ``12345678`` ``````int q = (i + start)/2; //average //... else if (q>4) { cout<<"Enter else"; divide(a,start,q,l); divide(a,q,i,l); }``````
You stop the recursion when the average is equal or less than 4.
However, your recursive calls are constantly increasing the numbers, so it will not end.
The if condition above has a return , which will terminate the loop.
please inform Wat can be the limiting condition?
Last edited on
I could run the below code for 16 elements but when the elements in the array is increased to 32 it again goes into an infinite loop
void divide(int a[], int start, int i, int l)
{
cout<<"Enter Divide";
int q = (i - start)/2;
cout<<q<<endl;
l++;
if (q == 4)
{
cout<<"Enter Sum";
cout<<"The sum of the elements is :"<<add1<<endl;
cout<<"The level is :"<<l<<endl;
return;
}
else
{
cout<<"Enter else";
divide(a,start,q,l);
divide(a,q,i,l);
}
}

Please let me know how to generalize the above.
Topic archived. No new replies allowed.