有序數(shù)組的合并問題

1.有兩個(gè)有序數(shù)組A,B。其中數(shù)組A的長(zhǎng)度足以放下A和B 的所有元素,現(xiàn)在要求將A和B數(shù)組合并到A中,合并后仍要求A是一個(gè)有序數(shù)組,給出你的算法。

/**
     * 
     * @param a
     *            ,a數(shù)組的長(zhǎng)度足夠長(zhǎng),足夠放下a和b的所有元素
     * @param b
     * @param size為數(shù)組a的有效元素個(gè)數(shù)
     *            <p>
     *            Description:
     *            </p>
     */
    public void arrayMerge(int a[], int b[], int size) {
        int storeIndex = size + b.length - 1;
        int i = size - 1;
        int j = b.length - 1;
        while (i >= 0 && j >= 0) {
            if (a[i] >= b[j]) {
                a[storeIndex] = a[i];// 大的元素直接放到最終位置
                i--;
                storeIndex--;
            } else if (a[i] < b[j]) {
                a[storeIndex] = b[j];// 將b中的元素插入到最終位置
                j--;
                storeIndex--;

            }
        }
        while (j >= 0) {
            a[storeIndex--] = b[j--];
        }
    }
public static void main(String[] args) {

        
        Sort s = new Sort();
        int a1[] = new int[8];
        a1[0] = 3;
        a1[1] = 8;
        a1[2] = 10;
        // int a2[] = { 1, 2, 4, 7 };
        int a2[] = { 7, 12 };
        s.arrayMerge(a1, a2, 3);
        System.out.println("after:" + Arrays.toString(a1));

    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容