Merge Sorted Array Algorithm

The Merge Sorted Array Algorithm is an efficient, stable, and comparison-based algorithm that is used to combine two or more sorted arrays into a single sorted array. This algorithm is a crucial part of the renowned Merge Sort, which is a divide-and-conquer sorting technique. The main idea behind the algorithm is to compare the first elements of the given sorted arrays and select the smallest element to be placed in the resulting merged array. This process is continued for the remaining elements in the given sorted arrays until all elements have been merged into the final sorted array. This algorithm is highly versatile and can be used to sort various data structures such as lists, arrays, and even large-scale data stored in databases or external storage. The efficiency of the Merge Sorted Array Algorithm lies in its linear time complexity, which is O(n+m), where n and m are the lengths of the two sorted arrays being merged. This is because the algorithm only needs to perform a single pass through both input arrays to generate the merged array. To implement the algorithm, two pointers or indices are used: one for each of the input arrays. These pointers start at the beginning of their respective arrays and are incremented as the elements are compared and added to the merged array. When one of the pointers reaches the end of its array, the remaining elements from the other array are added directly to the merged array, as they are already sorted. This algorithm can be implemented in various programming languages and can be easily adapted to handle additional constraints such as duplicate elements or custom comparison functions.
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int end = m + n - 1;
        m -= 1;
        n -= 1;
        while (m >= 0 && n >= 0) {
            if (A[m] > B[n]) 
                A[end--] = A[m--];
            else
                A[end--] = B[n--];
        }
        while (m >= 0) 
            A[end--] = A[m--];
        while (n >= 0)
            A[end--] = B[n--];
    }
};

LANGUAGE:

DARK MODE: