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.

C++:
01 class Solution {
02 public:
03     void merge(int A[], int m, int B[], int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int r=m+n1;
07         int p=m1;
08         int q=n1;
09         while((p>=0)&&(q>=0))
10         {
11             if(A[p]>B[q])
12             {
13                 A[r]=A[p];
14             }
15             else
16             {
17                 A[r]=B[q];
18             }
19         }
20         if(p<0)
21         {
22             while(r>=0)
23             {
24                 A[r]=B[q];
25             }
26         }
27     }
28 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s