inplace_merge() in C++

This C++ program merges two sequences using inplace_merge() algorithm. This algorithm combines the elements present in the two consecutive sorted ranges [first,middle) and [middle,last) into a combined sorted range [first,last).

Here is the source code of the C++ program which merges two sequences using inplace_merge() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to merge two sequences using inplace_merge() algorithm
  3.  */
  4. #include <iostream>    
  5. #include <algorithm>   
  6. #include <vector>       
  7. using namespace std;
  8.  
  9. void printVector(vector<int>& v)
  10. {
  11.     for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
  12.         cout << ' ' << *it;
  13.     cout << '\n';
  14. }
  15.  
  16. int main () {
  17.     vector<int> v1 = {5,10,15,20,25}, v2 = {50,40,30,20,10}, v3(10);
  18.     vector<int>::iterator it;
  19.  
  20.     sort(v1.begin(), v1.end());
  21.     sort(v2.begin(), v2.end());
  22.     it = copy(v1.begin(), v1.end(), v3.begin());
  23.     copy(v2.begin(), v2.end(), it);
  24.     inplace_merge(v3.begin(), it, v3.end());
  25.  
  26.     cout << "Vector v1 : ";
  27.     printVector(v1);
  28.     cout << "Vector v2 : ";
  29.     printVector(v2);
  30.     cout << "Vector v3 : ";
  31.     printVector(v3);
  32. }

$ gcc test.cpp
$ a.out
Vector v1 :  5 10 15 20 25
Vector v2 :  10 20 30 40 50
Vector v3 :  5 10 10 15 20 20 25 30 40 50

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.