// C++ program for the above approach
#include <iostream>
using namespace std;
// Function for merging the two sorted
// arrays
void merge(int a[], int l, int m, int r)
{
int s1 = m - l + 1;
int s2 = r - m;
// Create two temp arrays
int left[s1];
int right[s2];
// Copy elements to left array
for (int i = 0; i < s1; i++)
left[i] = a[l + i];
// Copy elements to right array
for (int j = 0; j < s2; j++)
right[j] = a[j + m + 1];
int i = 0, j = 0, k = l;
// Merge the array back into the
// array over the range [l, r]
while (i < s1 && j < s2) {
// If the current left element
// is smaller than the current
// right element
if (left[i] <= right[j]) {
a[k] = left[i];
i++;
}
// Otherwise
else {
a[k] = right[j];
j++;
}
k++;
}
// Copy the remaining elements of
// the array left[]
while (i < s1) {
a[k] = left[i];
i++;
k++;
}
// Copy the remaining elements of
// the array right[]
while (j < s2) {
a[k] = right[j];
j++;
k++;
}
}
// Function to sort the array over the
// range [l, r]
void mergesort(int arr[], int l, int r)
{
if (l < r) {
// Find the middle index
int mid = l + (r - l) / 2;
// Recursively call for the
// two halves
mergesort(arr, l, mid);
mergesort(arr, mid + 1, r);
// Perform the merge operation
merge(arr, l, mid, r);
}
}
// Function to sort an array for the
// last m elements are unsorted
void sortlastMElements(int arr[], int N,
int M)
{
int s = M + N - 1;
// Sort the last m elements
mergesort(arr, N, s);
// Merge the two sorted subarrays
merge(arr, 0, N - 1, N + M - 1);
// Print the sorted array
for (int i = 0; i < N + M; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int N = 3;
int M = 5;
int arr[] = { 2, 8, 10, 17, 15,
23, 4, 12 };
sortlastMElements(arr, N, M);
return 0;
}