Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 25, 2015 21:36
Show Gist options
  • Save dmnugent80/21e85ddd9d97e65a195a to your computer and use it in GitHub Desktop.
Save dmnugent80/21e85ddd9d97e65a195a to your computer and use it in GitHub Desktop.
Merge Sorted Array
/*
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