Topic:
Given sorted integer arrays A and B, merge B into a as one sorted array.
Note:
You could assume that A have enough space to the additional elements from B. The number of elements initialized in A and B is M and N respectively.
Test instructions to merge two ordered arrays into an array of them.
Title Analysis: The combination of numbers is not like a linked list, if you merge from the beginning, either move the data, or re-open a memory (redefining an array of m+n size), the n elements of the A array are empty, and we can merge from the back to the next without shifting.
Method One:
Merge from back to forward. The code is as follows:
void Merge_back (int a[], int m, int b[], int n) {int i=m-1;int j=n-1;int t=m+n-1;while (i>=0&&j>=0) {if (A[i] >=b[j]) {a[t]=a[i];i--;} else{a[t]=b[j];j--;} t--;} while (j>=0) {a[t]=b[j];j--;t--;}}
Method Two
Using the Insert sorting algorithm, the data that is assumed to be compared is the last data of a and the first data of B. If the last data of a is smaller than the first data of B, and if the last data of a is larger than the first data of B, the position of the first element of the appropriate B in the A array is found by using the insertion sorting algorithm.
The code is as follows:
void Insert_merge (int a[], int m, int b[], int n) {int i=m-1;int j=0;int t=m;for (t=m;t<m+n;t++) {if (A[i]<=b[j]) {a[t ]=b[j];j++;i++;} Else{int K=i;int X=b[j]; A[t]=a[i];while (X<a[k]) {a[k+1]=a[k];k--;} a[k+1]=x;i++;j++;}}}
The complete code is as follows:
<pre name= "code" class= "CPP" > #include <iostream> #include <string> #include <stdio.h>using namespace std;void merge_back (int a[], int m, int b[], int n); void insert_merge (int a[], int m, int b[], int n); void Mai N () {int A[5+6]={1,4,8,9,10};int b[6]={2,5,6,9,10,11};insert_merge (A, 5, B, 6);//merge_back (A, 5, B, 6); for ( int i=0;i<11;i++) {cout<<a[i]<< "";}} void Merge_back (int a[], int m, int b[], int n) {int i=m-1;int j=n-1;int t=m+n-1;while (i>=0&&j>=0) {if (A[i] >=b[j]) {a[t]=a[i];i--;} else{a[t]=b[j];j--;} t--;} while (j>=0) {a[t]=b[j];j--;t--;}} void Insert_merge (int a[], int m, int b[], int n) {int i=m-1;int j=0;int t=m;for (t=m;t<m+n;t++) {if (A[i]<=b[j]) {a[t ]=b[j];j++;i++;} Else{int K=i;int X=b[j]; A[t]=a[i];while (X<a[k]) {a[k+1]=a[k];k--;} a[k+1]=x;i++;j++;}}}
Operation results are: 1 2 4 5 6 8 9 9 10 10 11
Merge sorted array