Interview questions 10.01. Merge sort array (simple question)

Description Title:
to array A and B are given after two sort where the terminal A is sufficient buffer space to accommodate B. A method for the preparation of the A and B incorporated sort.

Initialize the number of elements A and B are m and n.

Example:

Input:
A = [1,2,3,0,0,0], m. 3 =
B = [2,5,6], n-=. 3

Output: [1,2,2,3,5,6]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/sorted-merge-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
solution:

class Solution {
    public void merge(int[] A, int m, int[] B, int n) {
        int right_border = A.length - 1;
        int cur = m - 1;
        for (int i = n - 1; i >= 0; ) {
            if(cur < 0){
                for (int j = 0; j <= right_border; j++) {
                    A[j] = B[j];
                }
                break;
            }
            if (A[cur] <= B[i]) {
                A[right_border] = B[i];
                right_border--;
                i--;
            } else {
                A[right_border] = A[cur];
                cur--;
                right_border--;
            }
        }
    }
}
Published 242 original articles · won praise 5 · Views 4372

Guess you like

Origin blog.csdn.net/weixin_43105156/article/details/104630265