-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedArrays.java
More file actions
42 lines (33 loc) · 1.26 KB
/
MergeSortedArrays.java
File metadata and controls
42 lines (33 loc) · 1.26 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
import java.util.Arrays;
public class MergeSortedArrays {
public static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArray = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
// Traverse both arrays and add elements to mergedArray in sorted order
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}
// Add remaining elements of arr1, if any
while (i < arr1.length) {
mergedArray[k++] = arr1[i++];
}
// Add remaining elements of arr2, if any
while (j < arr2.length) {
mergedArray[k++] = arr2[j++];
}
return mergedArray;
}
public static void main(String[] args) {
// Only one example is perfectly sufficient to show the functionality
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] merged = mergeArrays(arr1, arr2);
System.out.println("Array 1: " + Arrays.toString(arr1));
System.out.println("Array 2: " + Arrays.toString(arr2));
System.out.println("Merged Array: " + Arrays.toString(merged));
}
}