Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
01 public void merge(int A[], int m, int B[], int n) {
02 int lastA=m-1;
03 int lastB=n-1;
04 int last=m+n-1;
05
06 while(lastA>=0 && lastB>=0)
07 {
08 if(A[lastA]>=B[lastB])
09 {
10 A[last]=A[lastA];
11 lastA--;
12 last--;
13 }
14 else
15 {
16 A[last]=B[lastB];
17 lastB--;
18 last--;
19 }
20
21 }
22
23 while(lastB>=0)
24 {
25 A[last]=B[lastB];
26 lastB--;
27 last--;
28 }
29 }
02 int lastA=m-1;
03 int lastB=n-1;
04 int last=m+n-1;
05
06 while(lastA>=0 && lastB>=0)
07 {
08 if(A[lastA]>=B[lastB])
09 {
10 A[last]=A[lastA];
11 lastA--;
12 last--;
13 }
14 else
15 {
16 A[last]=B[lastB];
17 lastB--;
18 last--;
19 }
20
21 }
22
23 while(lastB>=0)
24 {
25 A[last]=B[lastB];
26 lastB--;
27 last--;
28 }
29 }
没有评论:
发表评论