---
# System prepended metadata

title: Question 88. Merge Sorted Array
tags: [leetcode]

---

###### tags: `leetcode`
# Question 88. Merge Sorted Array
### Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
### Solution:
Compare the big number and put the bigger number at the latter position of num1 array.
### AC code
code1
```cpp=
#include <algorithm>

class Solution {
public:
    void merge(vector<int>& n1, int m, vector<int>& n2, int n) {
        int l = m+n;
        for(int i = l-n, j = 0 ; i < l, j < n; i++, j++){
            n1[i] = n2[j];
        }
        sort(n1.begin(), n1.end());
};
```

code2
```cpp=
class Solution {
public:
    void merge(vector<int>& n1, int m, vector<int>& n2, int n) {
        int l = m+n-1;
        int i = m-1;
        int j = n-1;
        while(i >=0 && j >=0){
            if(n1[i] > n2[j]){
                n1[l--] = n1[i--];
            }
            else{ //n2 > n1
                n1[l--] = n2[j--];
            }
        }
        while(j >= 0){
            n1[l--] = n2[j--];
        }
    }
};
```