Users Online

· Guests Online: 98

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Merge Two Sorted Vectors

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.95 seconds
10,837,344 unique visits