-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge Without Extra Space.java
73 lines (66 loc) · 1.71 KB
/
Merge Without Extra Space.java
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
72
73
//{ 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)
{
// code here
int i=n-1;
int j=0;
while(i>=0 && j<m)
{
if(arr1[i]>arr2[j])
{
long temp=arr1[i];
arr1[i]=arr2[j];
arr2[j]=temp;
i--;
j++;
}
else
{
break;
}
}
Arrays.sort(arr1);
Arrays.sort(arr2);
}
}