Merge two ordered arrays into a new ordered array

Source: Internet
Author: User

Question: There are two ordered arrays A and B, which need to be merged into a new ordered array.

The simple idea is to put it in a new array and then sort it. However, this does not reflect any algorithms. Here we are not using sorting algorithms such as quick sorting. The key is how to useOrderedThis condition is known. You can think like this. If the two source arrays have different lengths, then if the short arrays are used up, they are all put into the new array, then the rest of the long array can be directly put into the new array.

Public class mergetwosortedarrays {public static int [] merge (INT [] A, int [] B) {int Lena =. length; int lenb = B. length; int [] C = new int [Lena + lenb]; int I = 0, j = 0, K = 0; // array A, B, c Index while (I <Lena & J <lenb) {if (a [I] <B [J]) c [k ++] = A [I ++]; elsec [k ++] = B [J ++];} while (I <Lena) c [k ++] = A [I ++]; while (j <lenb) C [k ++] = B [J ++]; return C ;} public static void main (string [] ARGs) {int [] C = merge (New int [] {1, 2, 3, 4}, new int [] {0, 2, 4, 5, 6, 7, 8}); For (INT I = 0; I <C. length; I ++) system. out. println (C [I]) ;}}


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.