@Muthu: Sort the data. Then start two indices: i1 = 0 to n-3, i2 = i1+1 to n-2. Inside these two loops, set i3 = i2+1 and i4 = n-1. Then loop while i3 < i4, incrementing i3 if a[i1]+a[i2]+a[i3]+a[i4] < num, decrementing i4 if a[i1]+a[i2]+a[i3]+a[i4] > num, or outputting the result if equality.
Dave On Aug 28, 1:26 am, muthu raj <[email protected]> wrote: > @Dave: Explain your O(n3) solution please > *Muthuraj R > IV th Year , ISE > PESIT , Bangalore* > > On Sat, Aug 27, 2011 at 11:10 PM, Mohit Goel <[email protected]>wrote: > > > > > This code may also work .....give any counter examples... > > > #include<iostream> > > using namespace std; > > void find_sum(int num,int k,int j,int b); > > void display(int i,int j); > > #define MAX 8 > > > int res[4]; //array to store > > 4 numbers.. > > int arr[MAX] ={2,3,4,1,6,9,8,10}; > > int main() > > { > > int b,k,j,num; > > cout<<"enter desired number"<<"\n"; > > cin>>num; > > k=0; > > j=b=0; > > find_sum(num,k,j,b); > > > return 0; > > } > > void find_sum(int num,int k,int j,int b) > > { > > int p,i; > > if(k< MAX) > > { > > if(j==3 && arr[k]== num ) > > { > > res[b]=arr[k]; > > display(0,b); //FOUND 4 NUMBER ,PRINT THEM > > > } > > else if(j == 3 && arr[k]!=num) > > { > > for(p=k+1;p<MAX;p++) > > { > > if(arr[p] == num) > > { > > res[b] =arr[p]; > > display(0,b); //FOUND 4 NUMBER ,PRINT THEM > > > break; > > > } > > } > > > } > > else > > { > > for(i=k;i<MAX;i++) > > { > > res[b] =arr[i]; > > find_sum(num-arr[i],i+1,j+1,b+1); > > > } > > } > > } > > } > > > void display(int i,int j) > > { > > cout<<"\n"; > > int k; > > for(k=0;k<=j;k++) > > cout<<" "<<res[k]; > > } > > > -- > > You received this message because you are subscribed to the Google Groups > > "Algorithm Geeks" group. > > To post to this group, send email to [email protected]. > > To unsubscribe from this group, send email to > > [email protected]. > > For more options, visit this group at > >http://groups.google.com/group/algogeeks?hl=en.- Hide quoted text - > > - Show quoted text - -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
