Quickly merging two sorted arrays using std::merge() in C++ STL(cute ho ap)

C++Server Side ProgrammingProgramming

In this article we will be discussing how we can quickly merge two sorted arrays using std::merge() function in C++ STL.

So, before solving the problem let's first discuss the std::merge() in C++ STL.

What is std::merge()?

std::merge() function is an inbuilt function in C++ STL, which is defined in the <algorithm> header file. merge() is used to merge two sorted ranges or series. This function combines two sorted ranges to make one single sorted range. All the elements are compared using less than operator (<) so the third range is also sorted by on its own.

How we will quickly merge two sorted arrays using std::merge()?

We are given the two sorted arrays which are arr1[] and arr2[] and the task is to merge those two sorted arrays and store it in another empty array which can be arr3[], using the function merge() available in C++ STL.

  • First we will calculate the size of both arrays arr[size_arr] and brr[size_brr] and define a third array whose size is the sum of sizes of both the arrays final[size_arr+size_brr].

  • Then we will merge the two arrays into the third array using merge() function like merge(arr, (arr + size_arr), brr, (brr + size_brr), final);

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
   int arr[] = {1, 2, 3};
   int size_arr = sizeof(arr)/sizeof(arr[0]);
   int brr[] = {4, 5, 6};
   int size_brr = sizeof(brr)/sizeof(brr[0]);
   int final[size_arr + size_brr];
   merge(arr, (arr + size_arr), brr, (brr + size_brr), final);
   cout<<"Final array after merging the elements is: ";
   for (int i = 0; i < (size_brr + size_arr); i++)
      cout << final[i] << " ";
   return 0;
}

Output

Final array after merging the elements is: 1 2 3 4 5 6
raja
Published on 17-Apr-2020 10:02:21
Advertisements