Java solution A special array merging problem _java

Source: Internet
Author: User
Given two sorted arrays A and B, where the end of a has enough space to hold B, write a method to merge B into a and sort.

When you get this question, the most immediate idea is to compare the elements in A and B, and insert the array in order until you have traversed all the elements in A and B. But there is a bad place to do this: if the insertion position of an element is at the front of array A, then the original array must be moved backwards. This will increase overhead. But we can use another method to insert the element at the end of the array A. So we don't get the element moving! The code is as follows:
Copy Code code as follows:
/*
* Number of actual elements in lasta:a lastb:b the actual number of elements in the Mergeindex is the actual space size of the new array
*/
public static void MergeOrder (int[] A, int[] b, int lasta, int lastb) {
int indexa = lastA-1;
int indexb = lastB-1;
int mergeindex = Lasta + lastB-1;
while (indexa >= 0 && indexb >= 0) {
if (A[indexa] > B[indexb]) {
A[mergeindex] = A[indexa];
Mergeindex--;
Indexa--;
} else {
A[mergeindex] = B[indexb];
Mergeindex--;
Indexb--;
}
}

while (Indexb >= 0) {
A[mergeindex] = B[indexb];
Mergeindex--;
Indexb--;
}
}

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.