注册 登录
编程论坛 C++教室

这个程序如何编写?

纯情程序猿 发布于 2023-06-01 23:24, 662 次点击
在数组a和数组b中分别放入n和m个由小到大的有序整数,程序把两个数组中的数按由小到大的顺序归并到数组c中。
1 回复
#2
rjsp2023-06-02 08:56
C++的做法
程序代码:
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

int main( void )
{
    int a[] = { 2,3,4, 7,8,9 };
    int b[] = { 0,1, 5,6, 10 };
    int c[ size(a) + size(b) ];

    ranges::merge( a, b, c );
    ranges::copy( c, std::ostream_iterator<decltype(*c)>(cout," ") );
}


如果用C语言,或不允许用标准模板库的话
程序代码:
#include <stdio.h>

void merge( const int* first1, const int* last1, const int* first2, const int* last2, int* output )
{
    for( ; ; )
    {
        if( first1!=last1 && (first2==last2 || *first1<=*first2) )
            *output++ = *first1++;
        else if( first2!=last2 && (first1==last1 || *first2<*first1) )
            *output++ = *first2++;
        else
            break;
    }
}

int main( void )
{
    int a[] = { 2,3,4, 7,8,9 };
    int b[] = { 0,1, 5,6, 10 };
    int c[ sizeof(a)/sizeof(*a) + sizeof(b)/sizeof(*b) ];

    merge( a, a+sizeof(a)/sizeof(*a), b, b+sizeof(b)/sizeof(*b), c );
    for( size_t i=0; i!=sizeof(c)/sizeof(*c); ++i )
        printf( "%d ", c[i] );
}
1