在 Java 中合并两个有序数组
两个有序数组可以合并,以获得一个单独的合并后的有序数组。以下提供了一个示例。
Array 1 = 1 3 7 9 10 Array 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("
Array 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("
Array after merging: "); for (x = 0; x < n1 + n2; x++) System.out.print(merge[x] + " "); } }
输出
Array 1: 11 34 66 75 Array 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("
Array 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("
Array after merging: "); for (x = 0; x < n1 + n2; x++) System.out.print(merge[x] + " ");
广告