有序數組合並,例如:
數組 A=[100, 89, 88, 67, 65, 34],
B=[120, 110, 103, 79]
合並后的結果 result=[120, 110, 103, 79, 100, 89, 88, 67, 65, 34]
程序:
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] a = { 100, 89, 88, 67, 65, 34 }; int[] b = { 120, 110, 103, 79 }; int a_len = a.length; int b_len = b.length; int[] result = new int[a_len + b_len]; // i:用於標示a數組 j:用來標示b數組 k:用來標示傳入的數組 int i = 0; int j = 0; int k = 0; while (i < a_len && j < b_len) { if (a[i] >= b[i]) result[k++] = a[i++]; else result[k++] = b[j++]; } // 后面連個while循環是用來保證兩個數組比較完之后剩下的一個數組里的元素能順利傳入 while (i < a_len) { result[k++] = a[i++]; } while (j < b_len) { result[k++] = b[j++]; } System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); System.out.println(Arrays.toString(result)); } }
結果:
[100, 89, 88, 67, 65, 34] [120, 110, 103, 79] [120, 110, 103, 79, 100, 89, 88, 67, 65, 34]