Dominik
Dominik

Reputation: 1325

How to merge 2 arrays using pointers?

I am making a program to merge and sort 2 arrays. I am using function 'merge' to do this. Algorithm must be inline - count of operations should be proportional to dima + dimb. I can't use helper arrays. How can I make this without using external libraries - I suspect that I can make these using pointers?

int a[] = {1,4,4,5,8};
int b[] = {1,2,2,4,6,6,9};
constexpr size_t dima = (sizeof(a)/sizeof(*a));
constexpr size_t dimb = (sizeof(b)/sizeof(*b));
constexpr size_t dimc = dima + dimb;
int c[dimc];
merge(a,dima,b,dimb,c);

void merge(const int* a, size_t dima, const int* b, size_t dimb, int* 
 c){}

Upvotes: 0

Views: 142

Answers (2)

Ishpreet
Ishpreet

Reputation: 5880

void merge(const int* a, size_t dima, const int* b, size_t dimb, int* c){
    int i = 0, j = 0, k = 0;
    while(i < dima && j < dimb){
        if(*(a + i) <= *(b + j))       
            *(c + k++)=*(a + i++);     
        else *(c + k++)=*(b + j++);    
    }
    while(i < dima)
        *(c + k++)=*(a + i++);
    while(j < dimb)
        *(c + k++)=*(b + j++);
}

Live Code

Upvotes: 1

ChandlerPP
ChandlerPP

Reputation: 11

int a[] = {1,4,4,5,8};
    int b[] = {1,2,2,4,6,6,9};
    constexpr size_t dima = (sizeof(a)/sizeof(*a));
    constexpr size_t dimb = (sizeof(b)/sizeof(*b));
    constexpr size_t dimc = dima + dimb;
    int* c = new int[dimc];
    merge(a,dima,b,dimb,c);

    void merge(const int* a, size_t dima, const int* b, size_t dimb, int* 
     c){
            int a_t=0;
            int b_t=0;
            int insert_a=0,insert_b=0;
            for(int i=0; i<dima+dimb;i++)
            {
                insert_a=0;
                insert_b=0;
                if(a_t < dima)
                {
                    if(b_t < dimb)
                    {
                        if(a[a_t] < b[b_t])
                        {
                            insert_a=1;
                        }
                        else
                        {
                            insert_b=1;
                        }
                    }
                    else
                    {
                        insert_a=1;
                    }
                }
                else
                {
                    insert_b=1;
                }

                if(insert_a)
                {
                    c[i] = a[a_t++];
                }
                else if(insert_b)
                {
                    c[i] = b[b_t++];
                }
            }
       }

It should work, this is what you meant?

Upvotes: 1

Related Questions