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]
以上是 Java程序创建两个未排序数组的排序合并数组 的全部内容, 来源链接: utcz.com/z/338278.html