VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorted-merge-one-array/

⇱ Sorted merge in one array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorted merge in one array

Last Updated : 24 Nov, 2022

Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. 
Merge B into A in sorted order.

Examples: 

Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} 
 b[] = {16, 17, 19, 20, 22};;
Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22}

One way is to merge the two arrays by inserting the smaller elements in front of A, but the issue with this approach is that we have to shift every element to right after every insertion.
So, instead of comparing which one is a smaller element, we can compare which one is larger and then insert that element into the end of A.

Below is the solution for the above approach.


Output
Array A after merging B in sorted order : 
10 12 13 14 16 17 18 19 20 22 

Time Complexity: O(m+n).
Auxiliary Space: O(1)

Comment
Article Tags: