Skip to content

Instantly share code, notes, and snippets.

@fever324
Created January 13, 2015 11:55
Show Gist options
  • Select an option

  • Save fever324/0ca60250f04b6b85f3e3 to your computer and use it in GitHub Desktop.

Select an option

Save fever324/0ca60250f04b6b85f3e3 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 (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