-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
mergeSortedArray.java
52 lines (43 loc) Β· 1008 Bytes
/
mergeSortedArray.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
package BasicPractice;
public class mergeSortedArray {
public static void main(String[] args) {
int[] arr1 = { 10, 20, 30, 40 };
int[] arr2 = { 15, 18, 24, 30 };
int[] sorted = merge(arr1, arr2);
display(sorted); // 10 15 18 20 24 30 30 40
}
public static int[] merge(int[] arr1, int[] arr2) {
int i = 0, j = 0;
int[] sorted = new int[arr1.length + arr2.length];
int index = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
sorted[index] = arr1[i];
i++;
index++;
} else {
sorted[index] = arr2[j];
j++;
index++;
}
}
if (i < arr1.length) {
for (int pos = i; pos < arr1.length; pos++) {
sorted[index] = arr1[pos];
index++;
}
} else {
for (int pos = j; pos < arr2.length; pos++) {
sorted[index] = arr2[pos];
index++;
}
}
return sorted;
}
public static void display(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}