0

Sort 2 unsorted arrays in one sorted array for best time complexity of O(n+m) in c++ language. How can we modify this code to make it for O(m+n) time complexity? The 2 array sizes should be different. Here the time complexity is O((m+n)log(m+n)). How to make it O(m+n) complexity?

#include <bits/stdc++.h> 
using namespace std; 
  
// Function to merge array in sorted order 
void sortedMerge(int a[], int b[], int res[],  
                                int n, int m) 
{ 
    // Concatenate two arrays 
    int i = 0, j = 0, k = 0; 
    while (i < n) { 
        res[k] = a[i]; 
        i += 1; 
        k += 1; 
    } 
    while (j < m) { 
        res[k] = b[j]; 
        j += 1; 
        k += 1; 
    } 
  
    // sorting the res array 
    sort(res, res + n + m); 
} 
  
// Driver code 
int main() 
{ 
    int a[] = { 10, 5, 15 }; 
    int b[] = { 20, 3, 2, 12 }; 
    int n = sizeof(a) / sizeof(a[0]); 
    int m = sizeof(b) / sizeof(b[0]); 
  
    // Final merge list 
    int res[n + m]; 
    sortedMerge(a, b, res, n, m); 
  
    cout << "Sorted merged list :"; 
    for (int i = 0; i < n + m; i++) 
        cout << " " << res[i]; 
    cout << "n"; 
  
    return 0; 
}

1 Answers1

0

Looking at your problem I think you forgot one little detail: is your arrays always guaranteed to contain postive integers?? If so, use a third array and store the two arrays values inside it. Then use radix sort to sort it, or if you know the range, use counting sort. I attached the link instead of explaining since explaining such complex sorting algorithms here would take way to long.

Counting sort: https://www.geeksforgeeks.org/counting-sort/#:~:text=Counting%20Sort,object%20in%20the%20output%20sequence.

Radix Sort: https://www.geeksforgeeks.org/radix-sort/

Yunfei Chen
  • 548
  • 5
  • 15