-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge 2 sorted arrays without using Extra space.
71 lines (64 loc) · 1.7 KB
/
Merge 2 sorted arrays without using Extra space.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.io.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases
while(t-->0){
String inputLine[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(inputLine[0]);
int m = Integer.parseInt(inputLine[1]);
long arr1[] = new long[n];
long arr2[] = new long[m];
inputLine = br.readLine().trim().split(" ");
for(int i=0; i<n; i++){
arr1[i] = Long.parseLong(inputLine[i]);
}
inputLine = br.readLine().trim().split(" ");
for(int i=0; i<m; i++){
arr2[i] = Long.parseLong(inputLine[i]);
}
Solution ob = new Solution();
ob.merge(arr1, arr2, n, m);
StringBuffer str = new StringBuffer();
for(int i=0; i<n; i++){
str.append(arr1[i]+" ");
}
for(int i=0; i<m; i++){
str.append(arr2[i]+" ");
}
System.out.println(str);
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution
{
//Function to merge the arrays.
public static void merge(long arr1[], long arr2[], int n, int m)
{
long[] arr = new long[n+m];
for(int i=0; i<n; i++)
{
arr[i]=arr1[i];
}
for(int i=0; i<m; i++)
{
arr[n+i]=arr2[i];
}
Arrays.sort(arr);
for(int i=0; i<n; i++)
{
arr1[i]=arr[i];
}
for(int i=0; i<m; i++)
{
arr2[i]=arr[n+i];
}
}
}