Added merge overlapping subintervals problem in cpp

pull/1079/head
rajen 2022-11-01 08:21:49 +05:30
parent 07d7d4aeb8
commit 094332879e
1 changed files with 50 additions and 0 deletions

View File

@ -0,0 +1,50 @@
#include<bits/stdc++.h>
using namespace std;
void merge(int arr1[], int arr2[], int n, int m) {
// code here
int i, k;
for (i = 0; i < n; i++) {
// take first element from arr1
// compare it with first element of second array
// if condition match, then swap
if (arr1[i] > arr2[0]) {
int temp = arr1[i];
arr1[i] = arr2[0];
arr2[0] = temp;
}
// then sort the second array
// put the element in its correct position
// so that next cycle can swap elements correctly
int first = arr2[0];
// insertion sort is used here
for (k = 1; k < m && arr2[k] < first; k++) {
arr2[k - 1] = arr2[k];
}
arr2[k - 1] = first;
}
}
int main() {
int arr1[] = {1,4,7,8,10};
int arr2[] = {2,3,9};
cout << "Before merge:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " ";
}
cout << endl;
for (int i = 0; i < 3; i++) {
cout << arr2[i] << " ";
}
cout << endl;
merge(arr1, arr2, 5, 3);
cout << "After merge:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " ";
}
cout << endl;
for (int i = 0; i < 3; i++) {
cout << arr2[i] << " ";
}
}