Skip to content

Latest commit

 

History

History
29 lines (24 loc) · 691 Bytes

43.md

File metadata and controls

29 lines (24 loc) · 691 Bytes

Merge Sorted Array

LeetCode Link

void merge(vector<int>& arr, int m, vector<int>& nums, int n) {
    vector<int> temp(m + n);
    int left = 0, right = 0, index = 0;

    while (left < m && right < n) {
        if (arr[left] <= nums[right]) {
            temp[index++] = arr[left++];
        } else {
            temp[index++] = nums[right++];
        }
    }

    while (left < m) {
        temp[index++] = arr[left++];
    }

    while (right < n) {
        temp[index++] = nums[right++];
    }

    // Copy the merged result back to the original array
    for (int i = 0; i < m + n; ++i) {
        arr[i] = temp[i];
    }
}