-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSortedArray.java
32 lines (28 loc) · 1.17 KB
/
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
class MergeSortedArray {
/*
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
Memory Usage: 39.4 MB, less than 23.26% of Java online submissions for Merge Sorted Array.
*/
public void merge(int[] A, int m, int[] B, int n) {
// In this code we start comparison from the last index
//first compare the last non-zero element of A with last element of B
while(m > 0 && n > 0){ //We need to make sure that both m and n should be initialized first
if(A[m-1]>B[n-1]) // comparing elements
{
A[m+n-1]=A[m-1]; //last element set
m--; //if the element is set from first array then decrease the m index
}
else
{
A[m+n-1]=B[n-1]; //last element set
n--; //if the element is set from second array then decrease the n index
}
}
// Special case where you dont have any initialize element in A and 1 elements in B then copy element of B in A
while(n>0)
{
A[m+n-1]=B[n-1];
n--;
}
}
}