-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeArrays.java
82 lines (66 loc) · 1.65 KB
/
MergeArrays.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
74
75
76
77
78
79
80
81
82
import java.util.Arrays;
public class MergeArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr1 = {1,3,5,7,9,11,13,0,0,0,0,0,0};
int[] arr2 = {0,2,4,6,8,12};
merge(arr1,7,arr2,6);
// int[] temp = new int[arr1.length+arr2.length];
// int index1 = 0;
// int index2 = 0;
// int i=0;
// while(index1<arr1.length && index2<arr2.length) {
// if(arr1[index1]<arr2[index2]) {
// temp[i] = arr1[index1];
// index1++;
// }
// else {
// temp[i] = arr2[index2];
// index2++;
// }
// i++;
// }//while
// /*upr waly code tak sir aik sub-array completely copy hogi
// remaining elements copy krny k lia nichy wala code h.*/
// while(index1<arr1.length) {
// temp[i] = arr1[index1];
// index1++;
// i++;
// }
// while(index2<arr2.length) {
// temp[i] = arr2[index2];
// index2++;
// i++;
// }
}
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int[] temp = new int[m+n];
int index1 = 0;
int index2 = 0;
int i=0;
while(index1<m && index2<n) {
if(nums1[index1]<nums2[index2]) {
temp[i] = nums1[index1];
index1++;
}
else {
temp[i] = nums2[index2];
index2++;
}
i++;
}//while
/*upr waly code tak sirf aik sub-array completely copy hogi
remaining elements copy krny k lia nichy wala code h.*/
while(index1<m) {
temp[i] = nums1[index1];
index1++;
i++;
}
while(index2<n) {
temp[i] = nums2[index2];
index2++;
i++;
}
System.out.println(Arrays.toString(temp));
}
}