-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP31_MergeTwoSortedArrays.java
More file actions
49 lines (38 loc) · 1.42 KB
/
Copy pathP31_MergeTwoSortedArrays.java
File metadata and controls
49 lines (38 loc) · 1.42 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
package programs;
import java.util.Arrays;
/**
* ============================================================
* PROGRAM 31: Merge Two Sorted Arrays into One
* ============================================================
* Problem: WAP to merge two sorted arrays of sizes M and N
* into a third sorted array of size M+N in O(M+N) time.
* ============================================================
*/
public class P31_MergeTwoSortedArrays {
public static int[] mergeSorted(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int[] merged = new int[n1 + n2];
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
// Copy remaining elements of arr1 (if any)
while (i < n1) merged[k++] = arr1[i++];
// Copy remaining elements of arr2 (if any)
while (j < n2) merged[k++] = arr2[j++];
return merged;
}
public static void main(String[] args) {
int[] a = {1, 3, 5, 7, 9};
int[] b = {2, 4, 6, 8, 10, 12, 14};
System.out.println("Array 1 : " + Arrays.toString(a));
System.out.println("Array 2 : " + Arrays.toString(b));
int[] result = mergeSorted(a, b);
System.out.println("Merged : " + Arrays.toString(result));
}
}