【问题标题】:How do I merge two arrays having different values into one array?如何将具有不同值的两个数组合并到一个数组中?
【发布时间】:2009-11-09 10:23:38
【问题描述】:

假设您有一个数组a[]=1,2,4,6 和第二个数组b[]=3,5,7。合并的结果应该包含所有值,即c[]=1,2,3,4,5,6,7。应该在不使用 <string.h> 的函数的情况下完成合并。

【问题讨论】:

  • osama,您可以编辑旧问题而不是提交新问题。
  • 不是重复的。在另一个问题中,osama(大概)询问了串联;这个问题是关于合并两个有序数组。
  • 这也是一个措辞更好的问题
  • 使用std::mergestd::inplace_merge

标签: c merge


【解决方案1】:

我还没有编译和测试以下代码,但我相当有信心。我假设两个输入数组都已经排序。与仅针对此示例的解决方案相比,要实现此通用目的还有更多工作要做。毫无疑问,我确定的两个阶段可以结合起来,但可能会更难阅读和验证;

void merge_example()
{
    int a[] = {1,2,4,6};
    int b[] = {3,5,7};
    int c[100];     // fixme - production code would need a robust way
                    //  to ensure c[] always big enough
    int nbr_a = sizeof(a)/sizeof(a[0]);
    int nbr_b = sizeof(b)/sizeof(b[0]);
    int i=0, j=0, k=0;

    // Phase 1) 2 input arrays not exhausted
    while( i<nbr_a && j<nbr_b )
    {
        if( a[i] <= b[j] )
            c[k++] = a[i++];
        else
            c[k++] = b[j++];
    }

    // Phase 2) 1 input array not exhausted
    while( i < nbr_a )
        c[k++] = a[i++];
    while( j < nbr_b )
        c[k++] = b[j++];
}

【讨论】:

    【解决方案2】:

    此时我正在自己学习 c,所以不要认为这是完美的解决方案,但也许您可以从我为解决您自己的问题所做的工作中获得一些想法。

    #include <stdio.h>
    #include <stdlib.h>
    
    int compare (const void * first, const void * second){
        return  *(int*)first - *(int*)second ;
    }
    
    int main(){
        int a[] = {1,2,4,6};
        int b[] = {3,5,7};
        size_t sizeA =sizeof(a)/sizeof(a[0]);
        size_t sizeB = sizeof(b)/sizeof(b[0]); 
        size_t sizeC = sizeA + sizeB; 
        /*allocate new array of sufficient size*/
        int *c = malloc(sizeof(int)*sizeC);
        unsigned i;
        /*copy elements from a into c*/
        for(i = 0; i<sizeA; ++i){
            c[i] = a[i];
        } 
        /*copy elements from b into c*/
        for(i = 0; i < sizeB; ++i){
            c[sizeA+i] = b[i];
        }
        printf("array unsorted:\n");
        for(i = 0; i < sizeC; ++i){
            printf("%d: %d\n", i, c[i]);
        }
        /*sort array from smallest to highest value*/
        qsort(c, sizeC, sizeof(int), compare);
        printf("array sorted:\n");
        for(i = 0; i < sizeC; ++i){
            printf("%d: %d\n", i, c[i]);
        }
        return 0;
    }
    

    【讨论】:

    • 鉴于输入数组已经排序,它们可以合并而不需要对结果进行排序。它应该是一个 O(N) 操作,但您已经创建了一个 O(N.logN) 操作。
    【解决方案3】:

    如果 2 个给定的数组已排序:

    while (true):
    {
        if (a[i] < b[j])
        {
            c[k] = a[i];
            i++;
        } else {
            c[k] = b[j]
            j++
        }
        k++
    }
    

    i,j,k 是索引,从零开始。请注意,此代码不检查数组长度。当你到达两个数组的末尾时,你也需要打破它。但是很容易对付。

    如果数组没有预先排序,您可以轻松地将它们连接起来并在它们上调用搜索函数,例如 BubbleSort 或 QuickSort。谷歌这些。

    【讨论】:

    • 同时(真)?另外,当一个索引超出范围时会发生什么?
    【解决方案4】:
    void merge(int *input1, size_t sz1, 
               int *input2, size_t sz2,
               int *output, size_t sz3) {
        int i = 0;
        int index1 = 0, index2 = 0;
    
        while (i < sz3 && index1 < sz1 && index2 < sz2)
            if (input1[index1] <= input2[index2])
                output[i++] = input1[index1++];
            else
                output[i++] = input2[index2++];
    
        if (index1 < sz1)
            for (; i < sz3 && index1 < sz1; ++i, ++index1)
                output[i] = input1[index1];
        else if (index2 < sz2)
            for (; i < sz3 && index2 < sz2; ++i, ++index2)
                output[i] = input2[index2];
    }
    

    你用那种方式:

    #define TAB_SIZE(x) (sizeof(x)/sizeof(*(x)))
    
    int tab1[] = { 1, 2, 4, 6 };
    int tab2[] = { 3, 5, 7 };
    
    int tabMerged[TAB_SIZE(tab1)+TAB_SIZE(tab2)];
    merge(tab1, TAB_SIZE(tab1), tab2, TAB_SIZE(tab2), tabMerged, TAB_SIZE(tabMerged));
    

    【讨论】:

      【解决方案5】:

      合并2个未排序的整数数组:

      void main()
      {
          clrscr();
          int A[10],B[10],C[26],a,b,n1,n2;
          cout<<"\n enter limit for array1     ";
          cin>>n1;
          cout<<"\n enter limit for array2     ";
          cin>>n2;
          a=0;b=0;int i=0;
          clrscr();
          while(1)
          {
              if(a<n1)
              {
                  cout<<"\n enter element "<<a+1<<"for array1   ";
                  cin>>A[a];
                  clrscr();
                  a++;
              }
              if(b<n2)
              {
                  cout<<"\n enter element "<<b+1<<"for array2  ";
                  cin>>B[b]; clrscr();
                  b++;
              }
              if(a==n1&&b==n2)
                  break;
          }
          a=0;b=0;
          cout<<"\n array merged";
          while(1)
          {
              if(a<n1)
              {
                  C[a]=A[a];
                  a++;
              }
              if(a>=n1&&b<n2)
              {
                  C[a]=B[b];
                  a++;b++;
              }
              if(a==(n1+n2))
              {
                  if(i<(n1+n2))
                  {
                      cout<<endl<<C[i];
                      i++;
                  }
                  else
                      break;
              }
          }
          getch();// \m/
      }
      

      【讨论】:

      • 发布 C++ 代码作为对标记为 C 的问题的答案具有值得商榷的价值。该问题从未使用 C++ 标记。
      【解决方案6】:

      这只是对账单的简单修改,这将采用 n 维数组:

          int main(void)
          {
              int m,n;
              int c[100];    
              printf("Enter Size of first Array: \n");
              scanf("%d",&m);
              printf("Enter Size of Second Array: \n");
              scanf("%d",&n);
      
              int a[m],b[n]; //Declaring array a and b with its size m and n accordingly
      
              int myval=m+n; //Size of the new array
      
              for(int i=0;i<m;i++){
                  printf("Enter value for first[%d]:",i); 
                  scanf("%d",&a[i]);
              }
      
              for(int i=0;i<m;i++){
                  printf("Enter value for Second[%d]:",i);    
                  scanf("%d",&b[i]);
              }
      
              int nbr_a = sizeof(a)/sizeof(a[0]); //this gives the actual size of an array
              int nbr_b = sizeof(b)/sizeof(b[0]);
              int i=0, j=0, k=0;
      
              // Phase 1) 2 input arrays not exhausted
              while( i<nbr_a && j<nbr_b )
              {
                  if( a[i] <= b[j] )
                      c[k++] = a[i++];
                  else
                      c[k++] = b[j++];
              }
      
              // Phase 2) 1 input array not exhausted
              while( i < nbr_a )
                  c[k++] = a[i++];
              while( j < nbr_b )
                  c[k++] = b[j++];
      
              for(i=0;i<myval;i++){
                  printf("c[%d]:%d\n",i,c[i] );
              }
          }
      

      【讨论】:

      • nbr_am不一样,nbr_bn不一样吗?在b 中输入m 而不是n 值不是错误吗?
      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2018-12-01
      • 1970-01-01
      • 2022-01-24
      • 2015-06-12
      • 2014-02-15
      相关资源
      最近更新 更多