-
Notifications
You must be signed in to change notification settings - Fork 5
/
MergeSortedWithoutExtraSpace.java
executable file
·46 lines (43 loc) · 1.42 KB
/
MergeSortedWithoutExtraSpace.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
package array;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MergeSortedWithoutExtraSpace {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String line=br.readLine();
String[] temp=line.trim().split("\\s+");
int[] arr1=new int[n];
for(int i=0;i<n;i++)
arr1[i]=Integer.parseInt(temp[i]);
int m=Integer.parseInt(br.readLine());
line=br.readLine();
temp=line.trim().split("\\s+");
int[] arr2=new int[m];
for(int i=0;i<m;i++)
arr2[i]=Integer.parseInt(temp[i]);
merge(arr1,arr2);
for(int o: arr1) System.out.print(o+" ");
System.out.println();
for(int o: arr2) System.out.print(o+" ");
br.close();
}
private static void merge(int[] arr1, int[] arr2){
for(int i=0;i< arr1.length;){
if(arr1[i]<=arr2[0])i++;
else{
int t=arr1[i];
arr1[i]=arr2[0];
arr2[0]=t;
i++;
for(int k=0;k< arr2.length-1 && arr2[k]>arr2[k+1] ;){
t=arr2[k];
arr2[k]=arr2[k+1];
arr2[k+1]=t;
k++;
}
}
}
}
}