Note that there are some explanatory texts on larger screens.

plurals
  1. POMerging 2 arrays by pointers
    text
    copied!<pre><code>/*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&lt;iostream.h&gt; #include&lt;conio.h&gt; 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&lt;(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&lt;m&amp;&amp;j&lt;n;) { if (*(ptr1+i) &gt; *(ptr2+j)) { *(p+k)=*(ptr1+i); i++;k++; } else { *(p+k)=*(ptr2+j); j++;k++; } } if(i==m) while(j&lt;n) { *(p+k)=*(ptr2+j); j++;k++; } else if(j==n) while(i&lt;m) { *(p+k)=*(ptr1+i); i++;k++; } cout&lt;&lt;"\n\n"; for(i=0;i&lt;k;i++) cout&lt;&lt;*(p+i)&lt;&lt;" "; getch(); delete p; } void main() { clrscr(); int i,j,k,a,b; cout&lt;&lt;"\nEnter the size of the first array first array : "; cin&gt;&gt;a; cout&lt;&lt;"\nEnter the size of second array : "; cin&gt;&gt;b; int *p1=new int[a], *p2=new int[b]; cout&lt;&lt;"\nEnter the elements of the first array : "; for(i=0;i&lt;a;i++) cin&gt;&gt;*(p1+i); cout&lt;&lt;"\nEnter the elements of the second array : "; for(i=0;i&lt;b;i++) cin&gt;&gt;*(p2+i); for(i=1;i&lt;a;i++) //insertion sort to sort 1st array in ascending order { k=*(p1+i); for(j=i-1;j&gt;=0&amp;&amp;*(p1+j)&gt;k;j--) *(p1+j+1)=*(p1+j); *(p1+j+1)=*(p1+j); } for(i=1;i&lt;b;i++) //insertion sort to sort the 2nd array in descending order { k=*(p2+i); for(j=i-1;j&gt;=0&amp;&amp;*(p2+j)&gt;k;j--) *(p2+j+1)=*(p2+j); *(p2+j+1)=*(p2+j); } for(i=0;i&lt;k;i++) cout&lt;&lt;*(p1+i)&lt;&lt;" "; cout&lt;&lt;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; } </code></pre> <p>The merge function is working perfect, but I don't understand why the insertion sort is not working propoerly. Can anyone help?</p> <p>I checked the merge separately by using sorted static array, as shown at the end of the code, the the merging worked fine, but when I used dynamic allocation, the code did not work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload