1999_1_fp

下面程序的功能是从键盘读取A,B数组的元素,A,B数组均已从小到大排好序(A,B数组各自无相同元素),现将A,B合并为数组C,同样要求数组C也是从小到大排好序(A,B数组有相同元素时保留一个)。程序中n表示数组A,B的长度。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdio>
using namespace std;
const int n=8;
const int m=2*n;
int a[n+1],b[n+1],c[m+1];
void copy(int &x,int &y,int &i,int &j){
    i=i+1;y=x;j=j+1;
}
int main(){
    int i,j,k;
    for ( i = 1; i <=n; i++)cin>>a[i];
    for ( i = 1; i <=n; i++)cin>>b[i];
    i=1;j=1;k=1;
    ___(1)____;
    while(___(2)____){
        if(a[i]<b[j])copy(a[i],c[k+1],k,i);
        else if (b[j]<a[i])copy(b[j],c[k+1],k,j);
        else{
            copy(a[i],c[k+1],k,i);
            ___(3)____;
        }
    }
    while(___(4)___)copy(a[i],c[k+1],k,i);
    while(___(5)___)copy(b[j],c[k+1],k,j);
    for ( i = 1; i <=k; i++)cout<<" "<<c[i];
   
        
}
Scroll to Top