【Code】合并两个有序数组

一、演示

两个指针分别指向,数组a和数组b的首位置。

  1. 比较两个指针所指元素的值。
  2. 将小的值赋值给合并后的数组,并且值小的指针迁移
  3. 继续第一步。

二、代码

public class Merge {

    public static void main(String[] args) {
        int[] a = new int[]{1, 3, 5, 7};
        int[] b = new int[]{2, 4, 6, 8};
        int[] mergeArray = mergeArrays(a, b);
        for (int i = 0; i < mergeArray.length; i++) {
            System.out.println(mergeArray[i]);
        }
    }

    public static int[] mergeArrays(int[] a, int[] b) {
        if (a.length == 0) {
            return b;
        }
        if (b.length == 0) {
            return a;
        }
        int[] merged = new int[a.length + b.length];
        int aIndex = 0;
        int bIndex = 0;
        int mergedIndex = 0;
        while (aIndex < a.length && bIndex < b.length) {
            int smallerData = 0;
            if (a[aIndex] < b[bIndex]) {
                smallerData = a[aIndex];
                aIndex++;
            } else {
                smallerData = b[bIndex];
                bIndex++;
            }
            merged[mergedIndex] = smallerData;
            mergedIndex++;
        }
        /*下面的两个while只会有一个执行*/
        while (aIndex < a.length) {
            merged[mergedIndex] = a[aIndex];
            mergedIndex++;
            aIndex++;
        }
        while (bIndex < b.length) {
            merged[mergedIndex] = b[bIndex];
            mergedIndex++;
            bIndex++;
        }
        return merged;
    }
}
posted @ 2021-10-17 23:30  ibrake  阅读(71)  评论(0编辑  收藏  举报