1. 程式人生 > >java 有序數組合並

java 有序數組合並

right logs solid 一個 static sys left void import

有序數組合並,例如:

數組 A=[100, 89, 88, 67, 65, 34],

B=[120, 110, 103, 79, 66, 35, 20]

合並後的結果 result=[120, 110, 103, 100, 89, 88, 79, 67, 66, 65, 35, 34, 20]

程序:

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, 66, 35, 20]
[120, 110, 103, 100, 89, 88, 79, 67, 66, 65, 35, 34, 20]

java 有序數組合並