java 有序數組合并

來源:互聯網
上載者:User

標籤:有序數組   string   個數   result   rgs   print   style   stat   order   

有序數組合并,例如:

數組 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 有序數組合并

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.