Link copied to clipboard. Share away!

Dissmis

Published on 09 Mar 2020

The problem to merge two sorted arrays can be done in 3 different methods. They are

**Method 1: **By traversing both the arrays to keep track of the current element in each arrays and finding the minimum value among the two and updating the **output_array **with the least value.

**Method 2: **Concatenate the two arrays into one and then sorting the entire array.

**Method 3: **Another approach is by using min-heaps. Take first element from both the arrays and add it to the min-heap and output the root element from the min-heap to the **merged_sorted_array **and continue the same until all the array elements have been processed.

An easier approach to merge two sorted arrays would be by traversing both the arrays to keep track of current element in both the arrays, finding the least value among the two and updating the final array with the least value.

**Algorithm **

- Declare two arrays and input the array elements in both the arrays.
- Traverse both the arrays.
- Find the minimum element among the current two elements of both the arrays and update the output_array with the least value and increment its index to next position.

C

C++

Output

Input-
Enter the size of Array 1:5
Enter the size of Array 2:5
Input the Array 1 elements:1 2 3 4 5
Input the Array 2 elements:6 7 8 9 10
Output-
The Merged Sorted Array: 1 2 3 4 5 6 7 8 9 10

In this approach, two arrays are merged into one and then the merged array is sorted finally.

**Algorithm**

- Declare two arrays and input the array elements in both the arrays.
- Concatenate both the arrays.
- Sort the concatenated array.

C

C++

Output

Input-
Enter the size of Array 1:5
Enter the size of Array 2:5
Input the Array 1 elements:1 2 3 4 5
Input the Array 2 elements:6 7 8 9 10
Output-
The Merged Sorted Array: 1 2 3 4 5 6 7 8 9 10

Another approach is by using min-heaps. Take the first element from both the arrays and add it to the min-heap and output the root element from the min-heap to the **output_array **and continue the same until all the array elements have been processed.

**Algorithm**

- Declare two arrays and input the array elements in both the arrays.
- Take the first element from both the arrays and insert them into a min-heap.
- The root element of the min-heap (minimum element) is moved to the output_array and the index of the output_array is incremented.
- Now, take the next element from both the arrays and continue the same procedure.

If you have any feedback about this
article and want to improve this, please write to **enquiry@faceprep.in**

×