Advertisement
npsoni

Untitled

Sep 29th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. void merge(int A[], int B[], int C[], int N, int M) {
  6.   int i = 0, j = 0, m = 0;
  7.   while (i < N && j < M) {
  8.     if (A[i] < B[j])  
  9.       C[m++] = A[i++];
  10.     else
  11.       C[m++] = B[j++];
  12.   }
  13.  
  14.   // one of A or B will exhaust first, we'll copy the remaining to C
  15.   while (i < N)  // B exhauseted
  16.     C[m++] = A[i++];
  17.   while (j < M)  // A exhauseted
  18.     C[m++] = B[j++];
  19. }
  20.  
  21. int main() {
  22.   ifstream cin("input.txt");
  23.  
  24.   int N, M;
  25.   cin >> N >> M;
  26.   int A[N], B[M], C[N + M];
  27.   for (int i = 0; i < N; i++) cin >> A[i];
  28.   for (int i = 0; i < M; i++) cin >> B[i];
  29.  
  30.   merge(A, B, C, N, M);
  31.  
  32.   for (int i = 0; i < N + M; i++)
  33.     cout << C[i] <<" ";
  34.  
  35.   return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement