Explore
Placement Prep

Edit

Edit

# Merge two sorted arrays | Program in C and C++

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.

## Method 1 to merge two sorted arrays

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

1. Declare two arrays and input the array elements in both the arrays.
2. Traverse both the arrays.
3. 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

## Method 2 to merge two sorted arrays

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

Algorithm

1. Declare two arrays and input the array elements in both the arrays.
2. Concatenate both the arrays.
3. 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

## Method 3 to merge sorted arrays

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

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