Merge Sorted Array Problem Solution

Merge Sorted Array Problem: You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]

Merge Sorted Problem Solution

Problem Solution In Python

def merge(self, nums1, m, nums2, n):
        i=0
        for x in range(len(nums1)):
            if i>=n:
                break
            if nums1[x]==0:
                nums1[x]=nums2[i]
                i+=1           
        nums1.sort()

Problem Solution In Java

public void merge(int A[], int m, int B[], int n) {
        int insertIndex = m+n-1;
        int indexA = m-1,indexB = n-1;
        
        while(indexB>=0){
            if(indexA<0){
                A[insertIndex--] = B[indexB--];
            }else{
                if(B[indexB]>=A[indexA]){
                    A[insertIndex--] = B[indexB--];
                }else{
                    A[insertIndex--] = A[indexA--];
                }
            }
        }
    }

Problem Solution In C++

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=0, j=0;
        vector<int> nums;
        while(1)
        {
            if(i==m)
            {
                while(j<n)
                {
                    nums.push_back(nums2[j]);
                    j++;
                }
                break;
            }
            
            else if(j==n)
            {
                while(i<m)
                {
                    nums.push_back(nums1[i]);
                    i++;
                }
                break;
            }
            
            else
            {
                if(nums1[i] < nums2[j])
                {
                    nums.push_back(nums1[i]);
                    i++;
                }
                else
                {
                    nums.push_back(nums2[j]);
                    j++;
                }
            }
        }
        
        for(i=0; i<m+n; i++)
            nums1[i] = nums[i];
    }
};

Problem Solution In C

int compare (int *a, int *b){
    
    return *a > *b;
}

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){

    int i;
    
    for(i = 0; i < n; i++){
        
        nums1[m + i] = nums2[i];
    }
    
    qsort(nums1, nums1Size, sizeof(int), compare);
    
}

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment