一個 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