Created
January 13, 2015 11:55
-
-
Save fever324/0ca60250f04b6b85f3e3 to your computer and use it in GitHub Desktop.
Merge Sorted Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. | |
| */ | |
| public class Solution { | |
| public void merge(int A[], int m, int B[], int n) { | |
| int end = m + n - 1; | |
| m--; | |
| n--; | |
| for( ; end >= 0; end--){ | |
| // check B depletion | |
| if(n == -1) { | |
| break; | |
| } | |
| if(m > -1 && A[m] > B[n]) { | |
| A[end] = A[m--]; | |
| } else { | |
| A[end] = B[n--]; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment