From d4b94e4b27d8a2d3e8e8c5c4c20f9c1ef84e2d20 Mon Sep 17 00:00:00 2001 From: Suraj Kumar Modi <76468931+skmodi649@users.noreply.github.com> Date: Tue, 19 Oct 2021 18:40:00 +0530 Subject: [PATCH] chore(Java): add merge without extra space for two array (#592) --- algorithms/Java/README.md | 1 + .../arrays/merge-without-extra-space.java | 95 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 algorithms/Java/arrays/merge-without-extra-space.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 51c2359f..3590b541 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -10,6 +10,7 @@ - [K-th Element of Two Sorted Arrays](arrays/kth-element--orted-array.java) - [Trapping Rain Water](arrays/trapping-rain-water.java) - [Ugly Number](arrays/ugly-number.java) +- [Merge Without Extra Space](arrays/merge-without-extra-space.java) ## Graphs - [Dijkstras](graphs/Dijkstras.java) diff --git a/algorithms/Java/arrays/merge-without-extra-space.java b/algorithms/Java/arrays/merge-without-extra-space.java new file mode 100644 index 00000000..1db77fc7 --- /dev/null +++ b/algorithms/Java/arrays/merge-without-extra-space.java @@ -0,0 +1,95 @@ +// Program to merge two sorted arrays without any extra space in Java +/* +Author : Suraj Kumar Modi +Github : https://github.com/skmodi649 + */ + + +/** Algorithm : + * 1) Initialize i,j as n-1,0 where n is size of arr1 + * 2) Iterate through every element of arr1 and arr2 using two pointers i and j respectively + * while(i>=0 && j=0 && j arr2[j]) + { + int temp = arr1[i]; + arr1[i] = arr2[j]; + arr2[j] = temp; + } + i--; + j++; + } + Arrays.sort(arr1); + Arrays.sort(arr2); + } +} + + +/** TEST CASES : + * + * Test Case 1 : + * Input : n = 3 , m = 4 + * arr1[] = {1,27,36} arr2[] = {12,14,16,22} + * Output : + * 1 12 14 16 22 27 36 + * + * Test Case 2 : + * Input : n = 4 , m = 5 + * arr1[] = {0,12,21,27} arr2[] = {4,6,8,10,12} + * Output : + * 0 4 6 8 10 12 12 21 27 + */ + +/** + * Time Complexity : O((n+m)log(n+m)) + * Auxiliary Space Complexity : O(1) + */ + +