There are two sorted arrays, a1 and a2 of size n1 and size n2 respectively. array a1 is full, array a2 has exactly n1(size of array a1) empty space. Example, a1[]=1234, a2[]=56789_ _ _ _ Write a function to merge these two arrays to form a sorted array without any extra memory use.

Wednesday, February 3, 2010

#include<iostream.h>
#include<conio.h>
void main()
{    clrscr();
    int n,m,i,j,temp;
    cout<<"enter the size of first array: ";
    cin>>n;
    cout<<"enter the size of second array: ";
    cin>>m;
    int *p=new int[n];
    int *q=new int[n+m];
    cout<<"enter the sorted elements of first array: ";
    for(i=0;i<n;i++)
    cin>>p[i];
    cout<<"enter the sorted elements of second array: ";
    for(i=0;i<m;i++)
    cin>>q[i];
    i=0;j=0;
    while(1)
    {    while(1)
        {    if(p[i]<q[j])
            {    temp=m;
                for(temp=m;temp>=j;temp--)

                q[temp]=q[temp-1];

                m++;
                break;
            }
            j++;
            if(j==m)
            {    temp=n;
                for(i=0;i<temp;i++)
                {    q[m]=p[i];
                    m++;
                }
                cout<<"after sorting elements are: ";
                for(i=0;i<m;i++)
                cout<<q[i]<<",";
                getch();
                return;
            }
        }
        i++;
        n--;
        if(n==-1)
        {    for(i=0;i<m+n;i++)
            cout<<q[i];
            break;
        }
    }
    getch();

0 comments: