11.1 Given two sorted arrays A and B, where the end of a has enough buffer space to accommodate B. Write a method that merges B into a and sorts.
Solution:
There is enough buffering at the end of the known quantity Group A, no additional space is required. The process logic of a program is simple, which is to compare the elements in A and b one by one, and insert the array sequentially until all the elements in A and B are exhausted. The only problem with this is that if you insert an element into the front of the array A, you must move the original element back to make room. A better practice is to insert elements into the end of array A, where free space is available.
The following code implements this practice, starting with the end elements of arrays A and B, and placing the largest elements at the end of the array A.
C + + Implementation code:
#include <iostream>using namespacestd;voidMergeintA[],intB[],intLasta,intLastb) { inti=lasta-1; intj=lastb-1; intk=lasta+lastb-1; while(i>=0&&j>=0) { if(a[i]>B[j]) {A[k--]=a[i--]; } Else{a[k--]=b[j--]; } } while(j>=0) {a[k--]=b[j--]; }}intMain () {inta[ -]={1,3,5,7,9}; intb[7]={2,4,6,8,Ten, One, the}; Merge (A, B,5,7); for(auto t:a) cout<<t<<' '; cout<<Endl;}
careercup-Sorting and finding 11.1