-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionArray.java
More file actions
79 lines (68 loc) · 1.75 KB
/
unionArray.java
File metadata and controls
79 lines (68 loc) · 1.75 KB
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
74
75
76
77
78
79
import java.util.ArrayList;
import java.util.Arrays;
public class unionArray {
public static void main(String[] args)
{
ArrayList<Integer> join= new ArrayList<>();
arrayFunction obj= new arrayFunction();
int[] a1= {1,2,5,3,2};
int[] a2= {1,2,7,6};
join= obj.union(a1,a2);
System.out.println(join+ " "+ join.size());
}
}
class arrayFunction{
ArrayList<Integer> union(int[] a1, int[] a2)
{
ArrayList<Integer> join = new ArrayList<>(a1.length + a2.length);
Arrays.sort(a1);
Arrays.sort(a2);
int len= (a1.length > a2.length) ? a1.length :a2.length;
for(int i=0; i<len; i++)
{
try{
join.add(a1[i]);
join.add(a2[i]);
}
catch(Exception e){
continue;
}
}
sortArrayList(join);
return join;
}
void sortArrayList(ArrayList<Integer> al)
{
// insertion sort
for (int i = 1; i < al.size(); i++)
{
for(int j= i; j > 0; j--)
{
if( al.get(j)< al.get(j-1))
{
int temp= al.get(j);
al.set(j, al.get(j-1));
al.set(j-1, temp);
}
}
}
removeDuplicate(al);
}
void removeDuplicate(ArrayList<Integer> al)
{
int j=0;
for (int i = 1; i < al.size(); i++) {
if (al.get(i)!= al.get(j)) {
al.set(j+1, al.get(i));
j++ ;
}
}
j++;
int s= j;
while(s< al.size())
{
al.remove(s);
}
al.trimToSize();
}
}