一个 Java 程序,用来创建一个由两个无序数组合并而成的有序数组
为了创建一个由两个无序数组合并而成的有序数组,首先,让我们创建两个无序数组−
int[] arr1 = new int[] {50, 22, 15, 40, 65, 75};
int[] arr2 = new int[] {60, 45, 10, 20, 35, 56};现在让我们创建一个新的结果数组,它将包括合并数组−
示例
int count1 = arr1.length;
int count2 = arr2.length;
int [] resArr = new int[count1 + count2];
Now, we will merge both the arrays in the resultant array resArr:
while (i < arr1.length){
resArr[k] = arr1[i];
i++;
k++;
}
while (j < arr2.length){
resArr[k] = arr2[j];
j++;
k++;
}
现在让我们来看一个完整的示例
示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args){
int[] arr1 = new int[] {50, 22, 15, 40, 65, 75};
int[] arr2 = new int[] {60, 45, 10, 20, 35, 56};
System.out.println("1st Array = "+Arrays.toString(arr1));
System.out.println("2nd Array = "+Arrays.toString(arr2));
int count1 = arr1.length;
int count2 = arr2.length;
int [] resArr = new int[count1 + count2];
int i=0, j=0, k=0;
while (i < arr1.length) {
resArr[k] = arr1[i];
i++;
k++;
}
while (j < arr2.length) {
resArr[k] = arr2[j];
j++;
k++;
}
Arrays.sort(resArr);
System.out.println("Sorted Merged Array = "+Arrays.toString(resArr));
}
}输出
1st Array = [50, 22, 15, 40, 65, 75] 2nd Array = [60, 45, 10, 20, 35, 56] Sorted Merged Array = [10, 15, 20, 22, 35, 40, 45, 50, 56, 60, 65, 75]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序
C++
C#
MongoDB
MySQL
Javascript
PHP