在 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] + " ");
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP