-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMerging.java
66 lines (64 loc) · 1009 Bytes
/
Merging.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
import java.util.Scanner;
public class Merging {
public static int[] input()
{
Scanner s=new Scanner(System.in);
int size=s.nextInt();
int arr[]=new int[size];
for(int i=0;i<size;++i)
arr[i]=s.nextInt();
return arr;
}
public static void print(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static int[] merge(int a[],int b[])
{
int merged[]=new int[a.length+b.length];
int i=0,j=0,k=0;
while(i<a.length&&j<b.length)
{
if(a[i]<b[j])
{
merged[k]=a[i];
++i;
}
else if(a[i]>b[j])
{
merged[k]=b[j];
++j;
}
else
{
merged[k]=a[i];
merged[++k]=b[j];
++i;
++j;
}
++k;
}
while(i<a.length)
{
merged[k]=a[i];
++i;
++k;
}
while(j<b.length)
{
merged[k]=b[j];
++j;
++k;
}
return merged;
}
public static void main(String[] args)
{
int arr1[]=input();
int arr2[]=input();
int merged[]=merge(arr1,arr2);
print(merged);
}
}