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.

 1 public class Solution {
 2     public void merge(int A[], int m, int B[], int n) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         int k = m + n - 1, i = m - 1, j = n - 1;
 6         while(i >= 0 || j >= 0){
 7             if(i >= 0 && (j < 0 || A[i] > B[j])) A[k--] = A[i--];
 8             else A[k--] = B[j--];
 9         }
10     }
11 }

 

posted on 2013-11-13 08:19  Step-BY-Step  阅读(103)  评论(0编辑  收藏  举报

导航