美文网首页
合并两个有序数组

合并两个有序数组

作者: 码而优则仕 | 来源:发表于2020-12-19 12:09 被阅读0次
     public static void main(String args[]) {
            merge(new int[]{-1, 0, 1, 3, 4}, 5, new int[]{7, 8, 9, 10, 11}, 5);
        }
    
    public static void merge(int A[], int firstSize, int B[], int secondSize) {
            // B合并到A 中
            int mergeSize = firstSize + secondSize;
            int[] mergeArr = new int[mergeSize];
            int j = 0;
            int merge = 0;
            for (int i = 0; i < firstSize; i++) {
                int firstCurrent = A[i];
                int secondCurrent = B[j];
                while (secondCurrent <= firstCurrent && j <= (secondSize - 1)) {
                    mergeArr[merge] = secondCurrent;
                    secondCurrent = B[++j];
                    merge++;
                }
                mergeArr[merge] = firstCurrent;
                merge++;
                while (i == (firstSize - 1) && j <= (secondSize - 1)) {
                    mergeArr[merge] = B[j];
                    j++;
                    merge++;
                }
            }
            for (int dkd : mergeArr) {
                System.out.print(dkd);
                System.out.print(",");
            }
        }
    

    相关文章

      网友评论

          本文标题:合并两个有序数组

          本文链接:https://www.haomeiwen.com/subject/agbxnktx.html