samedi 27 juin 2015

How to merge three sorted arrays without using any unnecessary space?

For example I've written C++ code to merge three arrays, but here you can see that first I had to merge first two arrays and then merge its resulting array to third array..

while (p < n1 && q < n2)    // n1,n2,n3 are sizes of a,b,c respectively 
{
    if (a[p] < b[q])    
    {
        res[r] = a[p];  // res is array is intermediate merged array
        r++;
        p++;
    }
    else
    {
        res[r] = b[q];
        r++;
        q++;
    }
}

while (q < n2)
{
    res[r] = b[q];
    r++;
    q++;
}

while (p < n1)
{
    res[r] = a[p];
    r++;
    p++;
}

while (s < r && t < n3)
{
    if (res[s] < c[t])
    {
        res2[r2] = res[s];  // res2 is finally merged array
        r2++;
        s++;
    }
    else
    {
        res2[r2] = c[t];
        r2++;
        t++;
    }
}

while (s < r)
{
    res2[r2] = res[s];
    s++;
    r2++;
}

while (t < n3)
{
    res2[r2] = c[t];
    r2++;
    t++;
}

I don't want to use intermediate array in my program.Is there any way I can do it?

Also, Is there any methodology using which we can merge any number of sorted arrays in one go ?

Aucun commentaire:

Enregistrer un commentaire