C++ Program to Merge Two Sorted Vectors
Posted by Superadmin on August 10 2022 08:21:14

C++ Program to Merge Two Sorted Vectors

 

 

This C++ Program which combines two sorted arrays. The program uses two user-defined functions enter_elem( ) and comb( ). The function enter_elem( ) takes number of elements of the vector as the input and runs a for loop to push elements into the vector. The vectors are then sorted and passed into the function comb( ) which returns a combined vector. The elements of the combined vector are then output to the standard output stream.

 

Here is source code of the C++ program which combines two sorted arrays. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Combine two Sorted Arrays
  3.  */
  4.  
  5. #include<iostream>
  6. #include<vector>
  7. #include<algorithm>
  8. using namespace std;
  9.  
  10. /* Function to input vector elements */
  11. void enter_elem(vector<int>& a)
  12. {
  13.     int alen, val;
  14.     cout << "Enter number of elements : ";
  15.     cin >> alen;
  16.  
  17.     for (int i = 0; i < alen; i++)
  18.     {
  19.         cin >> val;
  20.         a.push_back(val);
  21.     }
  22. }
  23.  
  24. /* Function to combine two integer vectors */
  25. vector<int> comb(vector<int> a, vector<int> b)
  26. {
  27.     int alen = a.size();
  28.     int blen = b.size();
  29.     int tlen = alen + blen;
  30.     vector<int> c(tlen);
  31.     int i = 0, j = 0, k = 0;
  32.  
  33.     while (i < alen && j < blen)
  34.     {
  35.         if (a[i] < b[j])
  36.             c[k++] = a[i++];
  37.         else
  38.             c[k++] = b[j++];
  39.     }
  40.     while (i < alen)
  41.         c[k++] = a[i++];
  42.  
  43.     while (j < blen)
  44.         c[k++] = b[j++];
  45.  
  46.     return c;
  47. }
  48.  
  49. int main()
  50. { 
  51.     vector<int> a;
  52.     vector<int> b;
  53.  
  54.     cout << "Initialising vector A" << endl;
  55.     enter_elem(a);
  56.     sort(a.begin(), a.end());
  57.  
  58.     cout << "Initialising vector B" << endl;
  59.     enter_elem(b);
  60.     sort(b.begin(), b.end());
  61.  
  62.     vector<int> c = comb(a, b);
  63.     for (int i = 0; i < c.size(); i++)
  64.         cout << c[i] << "  ";
  65.     cout << endl;
  66. }

 

$ g++ main.cpp
$ ./a.out
Initialising vector A
Enter number of elements : 5
3 1 5 3 7
Initialising vector B
Enter number of elements : 3
8 5 10
1  3  3  5  5 7  8  10