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)
{
int add, counter;
cout<<"Enter sum 2";
cout<<"The recurrence level is:"<<l<<endl;
for( counter = ii ;counter <= jj; counter ++)
{
add = add + a[counter];
}
cout<<"The sum of the elements of the subproblem is :"<<add<<endl;
add = 0;
}
1
2
q = 4; //assignment
q == 4; //comparison 
Please let me know the limiting condition coz it is goin into an infinite loop.
Please indent your code and use meaningful names for your variables.
1
2
3
4
5
6
7
8
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)
{
int add1=0;
int add2=0;
cout<<"Enter Divide";
int q = (i - start)/2;
cout<<q<<endl;
l++;
if (q == 4)
{
cout<<"Enter Sum";
add1 = a[q+start-4]+a[q+start-1]+a[q+start-2]+a[q+start-3];
cout<<"The sum of the elements is :"<<add1<<endl;
cout<<"The level is :"<<l<<endl;
add2= a[i-q]+a[i-q+1]+a[i-q+2]+a[i-q+3];
cout<<"The sum is :"<<add2<<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.