-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSortedArrays.java
More file actions
38 lines (37 loc) · 1016 Bytes
/
Copy pathmergeSortedArrays.java
File metadata and controls
38 lines (37 loc) · 1016 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
32
33
34
35
36
37
38
//Question: Merge two sorted arrays in a single sorted array.
package arrays;
public class mergeSortedArrays {
public static void main(String[] args) {
int[] a={20, 32, 55, 69};
int[] b={11, 27, 43, 75, 89};
int[] arr=new int[a.length+b.length];
int i=0, j=0, k=0;
while(i<a.length && j<b.length){ // Main Algorithm
if(a[i]<=b[j]){
arr[k]=a[i];
i++;
k++;
}else{ // b[j]<=a[i]
arr[k]=b[j];
k++;
j++;
}
}
if(i==a.length){ // If a array's elements are end. Now take elements from b only.
while(j<b.length){
arr[k]=b[j];
k++;
j++;
}
}
if(j==b.length){ // If b array's elements are end. Now take elements from a only.
while(i<a.length){
k++;
i++;
}
}
for(int ele : arr){
System.out.print(ele+" ");
}
}
}