Problem
You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
Solution
#include <iostream>
using namespace std;
void merge_sort(int la[], int llen, int sa[], int slen)
{
int lpos = llen - 1;
int spos = slen - 1;
int cpos = llen + slen -1;
while(lpos >= 0 && spos >=0){
if(la[lpos] > sa[spos]){
la[cpos --] = la[lpos --];
}
else {
la[cpos --] = sa[spos --];
}
}
while(spos >= 0){
la[cpos -- ] = sa[spos --];
}
}
int main(int argc, char* argv[])
{
int a[30] = {1,2,5, 9, 20, 28, 34, 43, 51};
int b[5] = {0, 3, 4, 4, 12};
merge_sort(a, 9, b, 5);
for(int i = 0; i < 14; i++){
cout << a[i] << " ";
}
cout << endl;
return 0;
}