合并Java中的两个排序数组
可以合并两个排序的数组,以便获得单个结果排序的数组。一个例子如下。
Array 1 = 1 3 7 9 10Array 2 = 2 5 8
Merged array = 1 2 3 5 7 8 9 10
演示该程序的程序如下。
示例
public class Example {public static void main (String[] args) {
int[] arr1 = {11, 34, 66, 75};
int n1 = arr1.length;
int[] arr2 = {1, 5, 19, 50, 89, 100};
int n2 = arr2.length;
int[] merge = new int[n1 + n2];
int i = 0, j = 0, k = 0, x;
System.out.print("Array 1: ");
for (x = 0; x < n1; x++)
System.out.print(arr1[x] + " ");
System.out.print("\nArray 2: ");
for (x = 0; x < n2; x++)
System.out.print(arr2[x] + " ");
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j])
merge[k++] = arr1[i++];
else
merge[k++] = arr2[j++];
}
while (i < n1)
merge[k++] = arr1[i++];
while (j < n2)
merge[k++] = arr2[j++];
System.out.print("\nArray after merging: ");
for (x = 0; x < n1 + n2; x++)
System.out.print(merge[x] + " ");
}
}
输出结果
Array 1: 11 34 66 75Array 2: 1 5 19 50 89 100
Array after merging: 1 5 11 19 34 50 66 75 89 100
现在让我们了解上面的程序。
首先显示2个排序的数组arr1和arr2。演示此过程的代码段如下所示。
System.out.print("Array 1: ");for (x = 0; x < n1; x++)
System.out.print(arr1[x] + " ");
System.out.print("\nArray 2: ");
for (x = 0; x < n2; x++)
System.out.print(arr2[x] + " ");
使用while循环将排序后的数组合并为单个数组。在while循环之后,如果将任何元素保留在arr1或arr2中,则将它们添加到合并数组中。演示此过程的代码段如下所示。
while (i < n1 && j < n2) {if (arr1[i] < arr2[j])
merge[k++] = arr1[i++];
else
merge[k++] = arr2[j++];
}
while (i < n1)
merge[k++] = arr1[i++];
while (j < n2)
merge[k++] = arr2[j++];
最后,显示合并的数组。演示此过程的代码段如下所示。
System.out.print("\nArray after merging: ");for (x = 0; x < n1 + n2; x++)
System.out.print(merge[x] + " ");
以上是 合并Java中的两个排序数组 的全部内容, 来源链接: utcz.com/z/339823.html