问题描述
编写程序,在程序中实现 void merge(int *a, int *b , int m, int n, int *result)函数,该函数合并两个递增排序的整数数组a和b(a、b数组的长度都不超过10)。函数第一、二个参数分别表示数组a和b,第三个参数m表示数组a长度,第四个参数n表示b数组长度,最后一个参数result表示a、b数组合并后的数组。
该程序第一行输入一个正整数m,表示a数组的长度,第二行输入数组a的各个值(以空格隔开);第三行输入一个正整数n,表示b数组的长度,第四行输入b数组的各个值(以空格隔开)。程序输出数组a和b合并后的递增序列。
样例输入
3
4 8 20
4
1 2 5 8
样例输出
1 2 4 5 8 8 20
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n,m;
m=sc.nextInt();
int[] a=new int[m];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
n=sc.nextInt();
int[] b=new int[n];
for (int i = 0; i < b.length; i++) {
b[i]=sc.nextInt();
}
int[] result=new int[n+m];
merge(a,b,m,n,result);
}
public static void merge(int[] a, int[] b , int m, int n, int[] result)
{
for (int i = 0; i<m; i++) {
result[i]=a[i];
}
for (int i = m; i < n+m; i++) {
result[i]=b[i-m];
}
Arrays.parallelSort(result);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
}