/*
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
*/
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
//Do it backward
void MergeSortedArray(int *A, int m, int *B, int n){
int posA = m - 1, posB = n - 1, pos = m + n - 1, swap = 0;
for (; pos >= 0; --pos){
if (A[posA] > B[posB]){
A[pos] = A[posA];
posA--;
}
else if (A[posA] < B[posB]){
A[pos] = B[posB];
posB--;
}
else{
A[pos] = A[--pos] = A[posA];
posA--; posB--;
}
}
}
//Do it in-place
int main(){
int A[20] = {1,3,5,6,12,13,15,16,27,32};
int B[5] = {2,8,14,24,44};
MergeSortedArray(A, 10, B, 5);
for (int i = 0; i < (15); ++i){
cout << A[i] << ' ';
}
cout << endl;
return 0;
}
answered
24 Mar, 15:02
FH86
21●3
accept rate:
0%