2012-01-08 129 views
1
/*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; 
} 

合并函数工作完美,但我不明白为什么插入排序不能正常工作。谁能帮忙?通过指针合并2个数组

我使用排序后的静态数组单独检查了合并,如代码末尾所示,合并工作正常,但是当我使用动态分配时,代码无法工作。

+3

为什么不使用STL算法?这将是一个5班轮。 – inf 2012-01-08 20:56:15

+1

'void main()'是**无效C++ **。 (我也怀疑''也是。) – 2012-01-08 20:59:24

+0

我相信''是一个Win32ism。 – duskwuff 2012-01-08 21:04:21

回答

1
for(j=i-1;j>=0&&*(p1+j)>k;j--) 
    *(p1+j+1)=*(p1+j); 
*(p1+j+1)=*(p1+j); 

最后一行应改为

*(p1+j+1)=k 

否则你会因为在循环后j == -1得到一些虚假的数据。第二类也是一样。

此外,您的数组打印输出错误,应该使用a,而不是k作为上限。

您的合并函数颠倒了一个数组,但不是另一个。要么你必须按降序对第二个数组进行排序(如注释所示),或者更好的是,在合并函数的开始处移除反转,并按照正确的顺序对数组进行排序以开始。

最后,如果您使用描述性变量名称并正确缩进代码,那么您的代码将更容易阅读(并因此进行调试)。

+0

是啊,现在我明白了,我应该注意到它。它是一个愚蠢的错误!谢谢:) – Richie 2012-01-09 06:59:04

2

您还应该用delete []替换delete。

+0

hmmmm谢谢:) – Richie 2012-01-09 07:00:04