Created
February 25, 2015 21:36
-
-
Save dmnugent80/21e85ddd9d97e65a195a 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 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 indexInsert = m + n - 1; | |
int mm = m - 1; | |
int nn = n - 1; | |
while (mm >= 0 && nn >= 0){ | |
if (A[mm] > B[nn]){ | |
A[indexInsert--] = A[mm--]; | |
} | |
else{ | |
A[indexInsert--] = B[nn--]; | |
} | |
} | |
while (nn >= 0){ | |
A[indexInsert--] = B[nn--]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment