Java Merge two sorted arrays

Source: Internet
Author: User

Title: Make two sorted arrays into a new sorted array, give a=[1,2,3,4],b=[2,4,5,6], return [1,2,2,3,4,4,5,6]

challenges

Can you optimize your algorithm if one of the arrays is large and the other array is small?

Idea: The two pointers point to the beginning of two arrays, each with a value of two pointers with a smaller number, the pointer moves back until one of the arrays ends, and the element after another array pointer is connected to the new array.

About the situation of the challenge if a[0]>b[b.length-1]| | A[a.length-1]<b[0], depending on the situation, you can directly connect a to the back of B (or b connected to the back of a)

The code is as follows

Public int[] Mergesortedarray (int[] A, int[] B) {        int i=0;        int j=0;        int res[] = new Int[a.length+b.length];        int k=0;        while (i<a.length&&j<b.length) {            if (A[i]<=b[j]) {                res[k++]=a[i++];            } else{                res[k++]=b[j++];            }        }        if (i!=a.length) {for            (int a=i;a<a.length;a++) {                res[k++]=a[a];            }        } else{for            (int b=j;b<b.length;b++) {                res[k++]=b[b];            }        }        return res;    }}

Java Merge two sorted arrays

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.