Merge Sorted Array

Source: Internet
Author: User

test instructions; Merge A, B with an ordered array into a, a space sufficient
Idea 1: The basic idea is simple, open up an extra array, space complexity and time complexity are O (N)
Code Listing 1:
public class Solution {public    void merge (int a[], int m, int b[], int n) {        if (n = = 0) return;        if (M = = 0) {            system.arraycopy (B, 0, A, 0, N);            return;        }        int i =0, j=0, temp = 0,k=0;        int [] C = new Int[a.length];        while (I < m && J < N) {            while (I < M && A[i] <= b[j]) {                c[k + +] = a[i + +];            }            while (I < m && J < n && B[j] < A[i]) {                c[k + +] = b[j + +];            }        }        if (I < m) {            system.arraycopy (A, I, C, K, m-i);        }        if (J < n) {            system.arraycopy (B, J, C, K, n-j);        }        System.arraycopy (C, 0, A, 0, c.length);}    }
Idea 2: Reverse traversal from the tail, the large first into the array of the trailing space complexity of O (1), the time complexity of O (N)
Code Listing 2:
public class Solution {public    void merge (int a[], int m, int b[], int n) {        if (n = = 0) return;        if (M = = 0) {            system.arraycopy (B, 0, A, 0, N);            return;        }        int tail = m + n-1;        n--;m--;        while (M >= 0 && n >=0) {            A[tail--] = Math.max (A[m], b[n]);            if (A[m] >= b[n]) m--;            else n--;        }        while (n--> 0) {        //    a[tail--] = B[n];        }        if (n >= 0) {            system.arraycopy (b,0,a,0,n+1);}}    }



Merge Sorted Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.