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--;
}
}