如何将具有不同值的两个数组合并为一个数组?

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

我没有编译和测试以下代码,但我有理由相信。 我假设两个输入数组已经排序。 要做出这个通用目的还有很多工作要做,而不是只针对这个例子的解决方案。 毫无疑问,我确定的两个阶段可以合并,但也许更难以阅读和validation;

 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 

我正在为他们自己学习,所以不要把它作为完美的解决方案,但也许你可以从我所做的一些想法中解决你自己的问题。

 #include  #include  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 

如果对2个给定数组进行排序:

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

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

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

 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)); 

合并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>A[a]; clrscr(); a++; } if(b>B[b]; clrscr(); b++; } if(a==n1&&b==n2) break; } a=0;b=0; cout<<"\n array merged"; while(1) { if(a=n1&&b 

这只是简单修改bill fosters答案,它将采用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