/*Program to merge to arrays using pointers in descending order, when the first array is in ascending order
and the second array is in descending order*/
#include<iostream.h>
#include<conio.h>
void merge(int *ptr1, int *ptr2, int m, int n)
{
int *p=new int[m+n],i,j,k;
for(i=0,k=m-1;i<(m/2);i++,k--) //to reverse the fir``st array from ascending to descending
{
j=*(ptr1+i);
*(ptr1+i)=*(ptr1+k);
*(ptr1+k)=j;
}
for(i=0,j=0,k=0;i<m&&j<n;)
{
if (*(ptr1+i) > *(ptr2+j))
{
*(p+k)=*(ptr1+i);
i++;k++;
}
else
{
*(p+k)=*(ptr2+j);
j++;k++;
}
}
if(i==m)
while(j<n)
{
*(p+k)=*(ptr2+j);
j++;k++;
}
else if(j==n)
while(i<m)
{
*(p+k)=*(ptr1+i);
i++;k++;
}
cout<<"\n\n";
for(i=0;i<k;i++)
cout<<*(p+i)<<" ";
getch();
delete p;
}
void main()
{
clrscr();
int i,j,k,a,b;
cout<<"\nEnter the size of the first array first array : ";
cin>>a;
cout<<"\nEnter the size of second array : ";
cin>>b;
int *p1=new int[a], *p2=new int[b];
cout<<"\nEnter the elements of the first array : ";
for(i=0;i<a;i++)
cin>>*(p1+i);
cout<<"\nEnter the elements of the second array : ";
for(i=0;i<b;i++)
cin>>*(p2+i);
for(i=1;i<a;i++) //insertion sort to sort 1st array in ascending order
{
k=*(p1+i);
for(j=i-1;j>=0&&*(p1+j)>k;j--)
*(p1+j+1)=*(p1+j);
*(p1+j+1)=*(p1+j);
}
for(i=1;i<b;i++) //insertion sort to sort the 2nd array in descending order
{
k=*(p2+i);
for(j=i-1;j>=0&&*(p2+j)>k;j--)
*(p2+j+1)=*(p2+j);
*(p2+j+1)=*(p2+j);
}
for(i=0;i<k;i++)
cout<<*(p1+i)<<" ";
cout<<endl;
/* int c[]={3,5,7};
int d[]={8,6,4};
merge(c,d,3,3); */ To check
merge(p1,p2,a,b);
delete p1;
delete p2;
}
Функция слияния работает отлично, но я не понимаю, почему сортировка вставок не работает должным образом. Кто-нибудь может помочь?
Я проверил слияние отдельно, используя отсортированный статический массив, как показано в конце кода, слияние работало нормально, но когда я использовал динамическое размещение, код не работал.