首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过指针合并2个数组

通过指针合并2个数组
EN

Stack Overflow用户
提问于 2012-01-09 04:52:35
回答 2查看 4.5K关注 0票数 2
代码语言:javascript
复制
/*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;
}

合并功能运行得很好,但我不明白为什么插入排序不能正常工作。有人能帮上忙吗?

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-09 05:03:44

代码语言:javascript
复制
for(j=i-1;j>=0&&*(p1+j)>k;j--)
    *(p1+j+1)=*(p1+j);
*(p1+j+1)=*(p1+j);

最后一行应为

代码语言:javascript
复制
*(p1+j+1)=k

否则,您将在循环之后获得一些伪造的数据,因为j == -1。第二类也是如此。

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

合并函数可以反转一个数组,但不能反转另一个数组。要么您必须按降序对第二个数组进行排序(正如注释所说的那样),要么更好的做法是删除merge函数开头的反转,并以正确的顺序开始对数组进行排序。

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

票数 1
EN

Stack Overflow用户

发布于 2012-01-09 05:13:03

您还应该将delete替换为delete[]。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8781221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档