From 094332879e409a68cc4fc9f99d5d64b09c012a43 Mon Sep 17 00:00:00 2001 From: rajen <2019saurabh.borawake@ves.ac.in> Date: Tue, 1 Nov 2022 08:21:49 +0530 Subject: [PATCH] Added merge overlapping subintervals problem in cpp --- .../Arrays/merge-overlapping-subintervals.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/merge-overlapping-subintervals.cpp diff --git a/algorithms/CPlusPlus/Arrays/merge-overlapping-subintervals.cpp b/algorithms/CPlusPlus/Arrays/merge-overlapping-subintervals.cpp new file mode 100644 index 00000000..74f6a850 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/merge-overlapping-subintervals.cpp @@ -0,0 +1,50 @@ +#include + +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] << " "; + } + +} \ No newline at end of file