C Exercises: Merge one sorted array into another sorted array
C Array: Exercise-38 with Solution
Write a program in C to merge one sorted array into another sorted array.
N.B.: The size of first array is (m+n) but only first m locations are populated remaining are empty. The second array is of size equal to n.
Pictorial Presentation:

Sample Solution:
C Code:
#include <stdio.h>
void merge2arrs(int *bgArr, int bgArrCtr, int *smlArr, int smlArrCtr)
{
if(bgArr == NULL || smlArr == NULL)
return;
int bgArrIndex = bgArrCtr-1,
smlArrIndex = smlArrCtr-1,
mergedArrayIndex = bgArrCtr + smlArrCtr -1;
while(bgArrIndex >= 0 && smlArrIndex >= 0) {
if(bgArr[bgArrIndex] >= smlArr[smlArrIndex]){
bgArr[mergedArrayIndex] = bgArr[bgArrIndex];
mergedArrayIndex--;
bgArrIndex--;
} else {
bgArr[mergedArrayIndex] = smlArr[smlArrIndex];
mergedArrayIndex--;
smlArrIndex--;
}
}
if(bgArrIndex < 0)
{
while(smlArrIndex >= 0)
{
bgArr[mergedArrayIndex] = smlArr[smlArrIndex];
mergedArrayIndex--;
smlArrIndex--;
}
} else if (smlArrIndex < 0)
{
while(bgArrIndex >= 0)
{
bgArr[mergedArrayIndex] = bgArr[bgArrIndex];
mergedArrayIndex--;
bgArrIndex--;
}
}
}
int main()
{
int bigArr[13] = {10, 12, 14, 16, 18, 20, 22};
int smlArr[6] = {11, 13, 15, 17, 19, 21};
int i;
//--------------- print large array --------------------
printf("The given Large Array is : ");
for(i = 0; i < 7; i++)
{
printf("%d ", bigArr[i]);
}
printf("\n");
//--------------- print small array --------------------
printf("The given Small Array is : ");
for(i = 0; i < 6; i++)
{
printf("%d ", smlArr[i]);
}
printf("\n");
//--------------- print merged array --------------------
merge2arrs(bigArr, 7, smlArr, 6);
printf("After merged the new Array is :\n");
for(i = 0; i<13; i++)
{
printf("%d ", bigArr[i]);
}
return 0;
}
Sample Output:
The given Large Array is : 10 12 14 16 18 20 22 The given Small Array is : 11 13 15 17 19 21 After merged the new Array is : 10 11 12 13 14 15 16 17 18 19 20 21 22
Flowchart: 1

Flowchart: 2

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to find the pivot element of a sorted and rotated array using binary search.
Next: Write a program in C to rotate an array by N positions.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
C Programming - What is the argument for printf that formats a long?
Put an l (lowercased letter L) directly before the specifier.
unsigned long n; long m; printf("%lu %ld", n, m);
Ref : https://bit.ly/3dIwfkP
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises