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

编程入门 行业动态 更新时间:2024-10-25 17:26:29
本文介绍了如何将两个具有不同值的数组合并到一个数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设您有一个数组a[]=1,2,4,6和另一个数组b[]=3,5,7.合并结果应具有所有值,即c[]=1,2,3,4,5,6,7.应该不使用<string.h>中的函数来完成合并.

Suppose you have one array a[]=1,2,4,6 and a second array b[]=3,5,7. The merged result should have all the values, i.e. c[]=1,2,3,4,5,6,7. The merge should be done without using functions from <string.h>.

推荐答案

我尚未编译和测试以下代码,但我有足够的信心.我假设两个输入数组都已排序.与仅针对本示例的解决方案相反,还有更多工作要做以实现这一通用目的.毫无疑问,我确定的两个阶段可以合并,但也许很难阅读和验证;

I haven't compiled and tested the following code, but I am reasonably confident. I am assuming both input arrays are already sorted. There is more work to do to make this general purpose as opposed to a solution for this example only. No doubt the two phases I identify could be combined, but perhaps that would be harder to read and verify;

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++]; }

更多推荐

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

本文发布于:2023-05-27 23:11:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/306115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   如何将   组中   个数   并到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!