From 07d05b2c883f58dbfca52bdee2c9d2a9ac0e4427 Mon Sep 17 00:00:00 2001 From: Ekta kanojia <91015183+Ektakanojia@users.noreply.github.com> Date: Fri, 22 Oct 2021 18:44:52 +0530 Subject: [PATCH] chore(CPlusPlus): add merge two sorted in array (#612) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- .../Arrays/merge-two-sorted-array.cpp | 77 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 78 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/merge-two-sorted-array.cpp diff --git a/algorithms/CPlusPlus/Arrays/merge-two-sorted-array.cpp b/algorithms/CPlusPlus/Arrays/merge-two-sorted-array.cpp new file mode 100644 index 00000000..f3fb44d0 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/merge-two-sorted-array.cpp @@ -0,0 +1,77 @@ +//c++ program to merge two sorted array without using extra space. +//sample: input +//arr1[]= 1 4 7 8 10; +//arr2[]=2 3 9; +//sample output: +//arr1[]={1,2,3,4,7} +//arr2[]={8,9,10} +//Time complexity: O(n1*m1) ,n1 is for linear traversal and m1 is for reordering. +//space complexity:O(1) +#include +using namespace std; +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + + cout << endl; +} +void merge_array(int arr1[],int arr2[],int n1,int n2) +{ + for(int i=0;iarr2[0]) + { + int temp=arr1[i]; /* logic for swapping the elements */ + arr1[i]=arr2[0]; + arr2[0]=temp; + /* swap(arr1[i],arr2[0]); this is stl function to swap the element*/ + // after swapping the array element we need to sort the element of second array because array is sorted. + int key,j; + for(int i=1;i=0 && arr2[j]>key) + { + arr2[j+1]=arr2[j]; + j=j-1; + } + + arr2[j+1]=key; + } + + } + } +} + +int main() +{ + //declaring a array1 and array2, + int arr1[100],arr2[100]; + int n1,n2,i; + cout<<"Enter the element number of you want in array 1 and array2"<<" "; + cin>>n1>>n2; + //taking user input for the array1 element and array2 element. + cout<<"enter the element of array1"<<" "; + for(i=0;i>arr1[i]; + } + cout<<"enter the element of array2"<<" "; + for(i=0;i>arr2[i]; + } + //calling the merge array function. + merge_array(arr1,arr2,n1,n2); + //for printing the final array element. + cout << "arr1: "; printArray(arr1, n1); + cout << "arr2: "; printArray(arr2, n2); + return 0; + +} + diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index d82af5ed..128c6aae 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -25,6 +25,7 @@ - [Index of Smallest element of Array](Arrays/index-of-smallest-element-of-array.cpp) - [Move Zeros to End of The Array](Arrays/move-zeros-to-end-of-array.cpp) - [Kadane's Algorithm](Arrays/Kadane's-Algorithm.cpp) +- [Merge two sorted array without using extraspace](Arrays/merge-two-sorted-array.cpp) - [All unique triplet that sum up to given value](Arrays/three-sum.cpp) ## Dynamic-Programming