inplace_merge() in C++

inplace_merge(): This function is available in the file stl_algo.h. It merges two sorted ranges in place.

This function does not return anything or we can say that it is of void type. It merges two sorted and consecutive ranges, [__first,__middle) and [__middle,__last), and puts the result in [__first,__last). 

The output will be sorted. The sort is stable, that is, for equivalent elements in the two ranges, elements

Parameters: Three parameters are required for this function.

__first – An iterator. 

__middle – Another iterator.

 __last – Another iterator.

Syntax:

inplace_merge(__first, __middle, __last)

For Example:

arr = {1,6,14,15}, vec= {7,8,10,11}

First of all, copy all the elements into a single array.

inplace_merge(res.begin(),res.begin()+arr.size(),res.end()) =>It merges both arrays and array result becomes ={1,6,7,8,10,11,14,15}

Approach 

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<intarr = {161415};
    vector<intvec = {781011};

    sort(arr.begin(), arr.end());
    sort(vec.begin(), vec.end());
    vector<intres(arr.size() + vec.size());

    vector<int>::iterator it = copy(arr.begin(), arr.end(), 
res.begin());
    copy(vec.begin(), vec.end(), it);
    inplace_merge(res.begin(), res.begin() + arr.size(),
 res.end());

    for (int i = 0i < res.size(); i++)
        cout << res[i] << " ";

    return 0;
}


No comments:

Post a Comment