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

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

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

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:12:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/306142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何将   两个

发布评论

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

>www.elefans.com

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