Recursion in C

shirrrrrrrrrrr's Avatar, Join Date: Jun 2009
Newbie Member
I need help to solve this problem:

The function gets two
sorted arrays (together with their sizes), and fills the
third array using the contents of the two arrays, so that
the third array is also sorted

what is the stopping condiation? I am stuck and dont know how to start...
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Why do you need recursion for that simple task?
Let's say the arrays contain { 1,2,4,6,10} and {3,7,8,12}.
The result will be {1,2,3,4,6,7,8,10,12}.
Try doing it on paper a few times, you'll see how to do it then. That's how I solve programming puzzles.
shirrrrrrrrrrr's Avatar, Join Date: Jun 2009
Newbie Member
Quote:
Originally Posted by xpi0t0s View Post
Why do you need recursion for that simple task?
Let's say the arrays contain { 1,2,4,6,10} and {3,7,8,12}.
The result will be {1,2,3,4,6,7,8,10,12}.
Try doing it on paper a few times, you'll see how to do it then. That's how I solve programming puzzles.

yes, i solve it in a simple way but now i need to solve it with recursion...i am a beginer in C progrming and I don't know how to start writing it...what should bee my stoping condition? or how do i tell the function what to to? any way thank you fot your help
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
If you ask how to fix a clock with a sledgehammer, probably nobody will be interested to help you (though it might be possible).

Try to fix a clock with screwdriver.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Why do you need to solve it with recursion? Is this an assignment/homework/coursework?
Anyway, all loops can be replaced with tail recursion, for a description of this see http://en.wikipedia.org/wiki/Tail_recursion
mayjune's Avatar, Join Date: Jun 2009
Invasive contributor
as far as i can think, stopping condition whould be
if (index of 3rd array is equal to the sum of the first two array)
return final_array;

if i get the code, will upload it....
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
Hi man !

If you are still struggling to fix the clock with sledgehammer [], here is something that I wrote today :

Code: C
void RecursiveCombine(int A[], int SizeA, int B[], int SizeB, int C[], bool InitialCall=true)
{
    static int IndexA, IndexB, IndexC;

    if( InitialCall )   IndexA = IndexB = IndexC = 0;

    if( IndexA < SizeA )
        if( IndexB < SizeB )
            if( A[IndexA] < B[IndexB] )     C[IndexC++] = A[IndexA++];
            else                            C[IndexC++] = B[IndexB++];
        else
            C[IndexC++] = A[IndexA++];
    else
        if( IndexB < SizeB )                C[IndexC++] = B[IndexB++];
        else                                return;

    RecursiveCombine(A, SizeA, B, SizeB, C, false);
}

You can should call it this way :
Code: C
RecursiveCombine(X, sX, Y, sY, Z);
or this way :
Code: C
RecursiveCombine(X, sX, Y, sY, Z, true);
Hope that helps.