-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedArray.java
More file actions
31 lines (28 loc) · 953 Bytes
/
Copy pathMergeTwoSortedArray.java
File metadata and controls
31 lines (28 loc) · 953 Bytes
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
public class MergeTwoSortedArray {
public static void main(String[] args) {
System.out.println("welcome to merging sorted Arrays\n");
int[] arr1 = ArrayUtility.inputArray();
int[] arr2 = ArrayUtility.inputArray();
int[] mergedArr = merge(arr1, arr2);
System.out.println("your merged array is:");
ArrayUtility.displayArray(mergedArr);
}
public static int[] merge(int[] arr1,int[] arr2) {
int newSize = arr1.length + arr2.length;
int[] newArr = new int[newSize];
int i = 0, j = 0, k = 0;
while (i < arr1.length || j < arr2.length) {
if(j == arr2.length ||
(i < arr1.length && arr1[i] < arr2[j])) {
newArr[k] = arr1[i];
i++;
k++;
} else {
newArr[k] = arr2[j];
k++;
j++;
}
}
return newArr;
}
}