-
Notifications
You must be signed in to change notification settings - Fork 1
/
mergetwosortedarray2.java
54 lines (43 loc) · 1.34 KB
/
mergetwosortedarray2.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
package striver.striver;
import java.util.Arrays;
public class mergetwosortedarray2 {
public static void main(String[] args) {
int[] arr1 = {1, 3, 4 ,4, 5};
int[] arr2 = {2, 4, 5 ,6};
int[] mergedArray = mergeArrays(arr1, arr2);
System.out.print("Merged Array: ");
for (int i = 0; i < mergedArray.length; i++) {
System.out.print(mergedArray[i] + " ");
}
System.out.println();
}
public static int[] mergeArrays(int arr1[], int arr2[]) {
int n = arr1.length;
int m = arr2.length;
int[] mergedArray = new int[n + m];
int left = n - 1;
int right = m - 1;
int index = mergedArray.length - 1;
while (left >= 0 && right >= 0) {
if (arr1[left] > arr2[right]) {
mergedArray[index] = arr1[left];
left--;
} else {
mergedArray[index] = arr2[right];
right--;
}
index--;
}
while (left >= 0) {
mergedArray[index] = arr1[left];
left--;
index--;
}
while (right >= 0) {
mergedArray[index] = arr2[right];
right--;
index--;
}
return mergedArray;
}
}