This problem and the substitution space problem can almost be solved efficiently with one pattern, that is, the number of A1 and A2 is compared from a backward-forward method, and then the larger number is copied to the appropriate location A1. Preventing the use of the previous method leads to a large number of repetitive movements.
Specific ideas: Similar to the merge process in Merge_sort, you can first get the actual length of the merged A1 Array (a1.length+a2.length)
The last element in the two arrays is compared in turn, and the larger number is placed in the end of the a array, until the elements in the A1 are completed or the arrays in the A2 are compared.
Then simply insert the extra elements directly into the A1 front section.
The specific code is as follows:
1#include <iostream>2 using namespacestd;3 Const intMaxarray = -;4 /*5 Alen: Actual element length of array a6 Blen: The actual element length of array b7 Suppose there is sufficient space at the end of a to accommodate B8 */9 voidCombine_array (inta[maxarray+1],intB[],intAlenintBlen)Ten { One inti = Alen-1;//J points to the last element of a A intj = Blen-1;//I point to the last element of B - for(intK = alen + Blen-1; K >=0; k--)//insert from backward forward - { the if(A[i] > B[j]) {//Select the larger, followed by the tail -A[K] =A[i]; ---i; - } + Else{ -A[K] =B[j]; +j--; A } at while(I <0&&j>=0){//if B is remaining, move the remaining elements in B to the front of A; -A[K] =B[j]; ---J; - } - } - for(inti =0; i < Alen+blen; i++)//print out the merged array in { -cout << A[i] <<" "; to } +cout <<Endl; - } the intmain5 () * { $ inta[maxarray+1] = {1,3,5,7,8, A };Panax Notoginseng intB[] = { -, the, -, - }; -Combine_array (A, B,6,4); theSystem"Pause"); + return 0; A}
The resulting output is:
There are two ascending arrays of A1 and A2, where there is enough extra space at the end of the A1 to accommodate the A2, design a function that inserts all the numbers in the A2 into the A1 and all the numbers in ascending order.