题目:给定俩个排序后的数组A和B,其中A的末端有足够的缓存空间容纳B。编写一个方法,将B合并入A并排序。
方法一:先将B数组添加到A数组后面,再将A数组从0到加完B后长度进行排序。
import java.util.*;
import java.util.stream.StreamSupport;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
static int[] mergeArr;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[] arr = new int[n+m];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int[] arr2 = new int[m];
for(int i = 0;i<m;i++){
arr2[i] = input.nextInt();
}
mergeArr(arr,arr2);
}
public static void mergeArr(int[] arr1,int[] arr2){
int n = 0;
int m = arr2.length;
for(n =0;n<arr1.length;n++){
if(arr1[n] > arr1[n+1]){
break;
}
}
n++;
for(int i =n,j=0;j<m;j++,i++){
arr1[i] = arr2[j];
}
Arrays.sort(arr1,0,n+m);
System.out.println(Arrays.toString(arr1));
}
}
方法二:采用归并的思想
import java.util.*;
import java.util.stream.StreamSupport;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
static int[] mergeArr;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[] arr = new int[n+m];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int[] arr2 = new int[m];
for(int i = 0;i<m;i++){
arr2[i] = input.nextInt();
}
mergeArr(arr,arr2);
}
public static void mergeArr(int[] arr1,int[] arr2){
int n = 0;
int m = arr2.length;
for(n =0;n<arr1.length;n++){
if(arr1[n] > arr1[n+1]){
break;
}
}
n++;
int index = n+m-1,i = n-1,j = m-1;
while(i>=0 && j>=0){
if(arr1[i]>arr2[j]){
arr1[index--] = arr1[i--];
}
else{
arr1[index--] = arr2[j--];
}
}
while(j>=0){
arr1[index--] = arr2[j--];
}
System.out.println(Arrays.toString(arr1));
}
}