刷题No4. 两个有序数组合并为一个有序数组(java)【数组】

题目描述

给出两个有序的整数数组A和B,请将数组B合并到数组A中,变成一个有序的数组

import java.util.Arrays;
public class testNo4 {
    public static void main(String[] args) {
        testNo4 test = new testNo4();
        int[] num1 = {1,3,4,6,0,0,0,0};
        int[] num2 = {2,5,7,8};
        test.merge(num1,4,num2,4);

    }
    public void merge(int A[], int m, int B[], int n) {
        int i = m-1;
        int j = n-1;
        int t = m+n-1;
        while(i>=0 && j>=0){
            if(A[i] > B[j]){
                A[t--] = A[i--];
            }
            else{
                A[t--] = B[j--];
            }
        }
        while (j>=0){
            A[t--] = B[j--];
        }
        System.out.println(Arrays.toString(A));

    }

}
发布了46 篇原创文章 · 获赞 11 · 访问量 3600

猜你喜欢

转载自blog.csdn.net/qq_40664693/article/details/103806487