Merge Two Sorted Arrays in C Language
Merge Two Sorted Arrays in C Program Description:
We have covered the Merging of Two unsorted arrays in our earlier articles. In today’s article, We will look at a Program to Merge Two Sorted Arrays in C Programming Language. The Program should accept two sorted arrays from the user and merge two sorted arrays input by the user and output a single sorted array.
Here is the example input and Output of the program.
Excepted Input and Output:
Input:
Enter desired size for array1 (1-100): 10
Please enter array elements(10) in Ascending Order : 100 200 300 400 500 600 666 700 800 900
Enter desired size for array2 (1-100): 10
Please enter array elements(10) in Ascending Order : 111 222 333 444 555 777 888 999 1111 2222
Output:
Array-1: 100 200 300 400 500 600 666 700 800 900
Array-2: 111 222 333 444 555 777 888 999 1111 2222
Sorted Merged Array: 100 111 200 222 300 333 400 444 500 555 600 666 700 777 800 888 900 999 1111 2222
So when user provided two sorted arrays 100 200 300 400 500 600 666 700 800 900 and 111 222 333 444 555 777 888 999 1111 2222, Then the Program merged them in sorted order 100 111 200 222 300 333 400 444 500 555 600 666 700 777 800 888 900 999 1111 2222
📢This Program is Part of the Arrays Practice Programs Series.
Prerequisites:
It is recommended to know the basics of the Arrays and Functions in C language to better understand this program. Please check out following articles to learn more about them
- Arrays in C Language with Example Programs
- Functions and How to Create and Use Functions in C with Examples
- Passing Arrays to Functions in C
Merge Two Sorted Arrays in C Program Explanation:
Here is the step-by-step explanation of the Merge Two Sorted Arrays in C Program.
- Declare two arrays arr1[100] and arr2[100] as the input arrays. Also create a third array which is going to store the Merged Array. So declare sMergedArr[200], The sMergedArr can hold 200 elements, which is equal to the arr1+arr2 array’s max sizes. It is important for the sMergedArr to have the enough size to store the arr1 and arr2 arrays.
- Define two helper functions called
read() function and
display() function
- Both these functions take two formal arguments which are arr[] array and it’s size.
- The read() function takes the input from the user and updates the array elements
- The display() function prints the array elements on the console.
- Now, We need to take the two arrays from the user. (To be precise, Array size and Array elements)
- Get the
arr1 array size and elements from the user.
- Call the read() function to store the elements in arr1
- Similarly, get the arr2 array size and elements from the user.
- Once we got the both arrays(
arr1 and
arr2). Print the arrays on the console by calling the
display() funciton.
- display(arr1, size1);
- display(arr2, size2);
- Now, We need to Merge the Two Sorted Arrays.
- Initialize two variables i and j with zero(0). The i and j will keep track of the index of the arr1 and arr2 arrays respectively.
- Use a For Loop to Iterate over the
sMergedArr array. (from k=0 to k<(size1+size2)), For each iteration,
- Compare the arr1[i] and arr2[j] and copy the smallest number to the third array (i.e sMergedArr[k])
- So check the elements at the arr1[i] and arr2[j], If the arr1[i] is smaller than the arr2[j], Then insert the arr1[i] at sMergedArr[k] and increment the i and k
- If the arr2[j] is smaller than the arr1[i], Then copy the arr2[j] to sMergedArr[k] and Increment the j and k.
- If any of the arrays is reached the end, Then we need to copy the remaining elements directly to the third array.
- If the i is reached the size1 of the arr1, Then copy the remaining elements of the arr2 to sMergedArr – if(i >= size1)
- Similarly, If the j is reached the size( size2) of the arr2, Then copy the remaining elements of the arr1 to sMergedArr – if (j >= size2)
- Once the above Loop is completed, Then the third array i.e sMergedArr will contain the Merged Array in Sorted order.
- Display the Merged array on the console by calling the display() function – display(sMergedArr, tSize);. where tSize = size1+size2;
- Stop the program.
Program to Merge Two Sorted Arrays in C Language:
Here is the Program to Merge Two Sorted Arrays in C language and produce a Merged Sorted Array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
/* Program Merge two arrays and create third Array Author: SillyCodes.com */ #include <stdio.h> /** * @brief - Read the user input and update the 'arr' array * * @param arr - 'arr' array * @param size - size of the 'arr' array */ void read(int arr[], int size) { int i; // User input for array elements printf("Please enter array elements(%d) in Ascending Order : ", size); for(i = 0; i < size; i++) { // printf("arr[%d] : ", i); scanf("%d", &arr[i]); } } /** * @brief - Display the 'arr' array * * @param arr - Array * @param size - Array size */ void display(int arr[], int size) { int i; for(i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { // declare the 'arr1', 'arr2', and 'mergedArr' array int arr1[100], arr2[100], sMergedArr[200]; int i = 0, j = 0, k = 0, size1, size2, tSize; // Take the Array1('arr1') details from the user printf("Enter desired size for array1 (1-100): "); scanf("%d", &size1); // check for array bounds if(size1 >= 100 || size1 <= 0) { printf("Invalid Size, Try again \n"); return 0; } // User input for array elements read(arr1, size1); // Take the Array2('arr2') values from the user. printf("Enter desired size for array2 (1-100): "); scanf("%d", &size2); // check for array bounds if(size2 >= 100 || size2 <= 0) { printf("Invalid Size, Max Array size reached, Try again \n"); return 0; } // Take User input for array elements read(arr2, size2); tSize = size1 + size2; // Print the 'arr1' array printf("Array-1: "); display(arr1, size1); // Print the 'arr2' array printf("Array-2: "); display(arr2, size2); // Merge the two sorted arrays. for(k = 0; k < tSize; k++) { if(i >= size1) { // if we reached the end of the 'arr1' // copy remainig elements of 'arr2' to 'sMergedArr' sMergedArr[k] = arr2[j++]; } else if (j >= size2) { // if we reached to the end of the 'arr2' // then copy the remaining elements of the 'arr1' to 'sMergedArr' sMergedArr[k] = arr1[i++]; } else { // 'arr1' and 'arr2' are not empty // compare the present element and copy the smaller one to 'sMergedArr' array if(arr1[i] < arr2[j]) { sMergedArr[k] = arr1[i++]; } else { sMergedArr[k] = arr2[j++]; } } } // Print the merged Array printf("Sorted Merged Array: "); display(sMergedArr, tSize); return 0; } |
Note that we have defined two function read() and display() with two formal arguments.
Program Output:
Let’s compile and run the program using GCC compiler (Any compiler)
Compile the Program
$ gcc merge-two-sorted-arr.c
Run the program
Example 1: When first array ( arr1) and second array( arr2) are of same size.
1 2 3 4 5 6 7 8 9 |
$ ./a.out Enter desired size for array1 (1-100): 10 Please enter array elements(10) in Ascending Order : 100 200 300 400 500 600 666 700 800 900 Enter desired size for array2 (1-100): 10 Please enter array elements(10) in Ascending Order : 111 222 333 444 555 777 888 999 1111 2222 Array-1: 100 200 300 400 500 600 666 700 800 900 Array-2: 111 222 333 444 555 777 888 999 1111 2222 Sorted Merged Array: 100 111 200 222 300 333 400 444 500 555 600 666 700 777 800 888 900 999 1111 2222 $ |
Example 2: When the first Array ( arr1) is larger than the Second array( arr2).
1 2 3 4 5 6 7 8 9 |
$ ./a.out Enter desired size for array1 (1-100): 10 Please enter array elements(10) in Ascending Order : 1 1 2 2 3 4 5 6 7 8 Enter desired size for array2 (1-100): 5 Please enter array elements(5) in Ascending Order : 2 3 4 5 6 Array-1: 1 1 2 2 3 4 5 6 7 8 Array-2: 2 3 4 5 6 Sorted Merged Array: 1 1 2 2 2 3 3 4 4 5 5 6 6 7 8 $ |
As you can see from the above outputs, The program is able to Merge the two sorted arrays and generated the sorted array.
Let’s see another example, Where the first array( arr1) size is smaller than the second array( arr2).
Example 3: When the First Array( arr1) size is smaller than the Second Array( arr2).
1 2 3 4 5 6 7 8 9 |
$ ./a.out Enter desired size for array1 (1-100): 3 Please enter array elements(3) in Ascending Order : 11 22 33 Enter desired size for array2 (1-100): 6 Please enter array elements(6) in Ascending Order : 1 5 15 25 35 45 Array-1: 11 22 33 Array-2: 1 5 15 25 35 45 Sorted Merged Array: 1 5 11 15 22 25 33 35 45 $ |
Finally, Let’s look at another example when the array size went out of the bounds.
Example 4: When the array size is out of bounds.
1 2 3 4 5 6 7 |
$ ./a.out Enter desired size for array1 (1-100): 555 Invalid Size, Try again $ ./a.out Enter desired size for array1 (1-100): 0 Invalid Size, Try again $ |
As we can see from the above outputs, As excepted the program is generating the an error message( Invalid Size, Try again) on invalid size.
Related Array Programs:
- C Program to calculate Sum of all array Elements
- C Program to Calculate the Average of all array Elements
- C Program to find minimum element in Array
- C Program to Find Maximum Element in Array
- C Program to Find Second Largest Element in Array
- C Program to Insert an element in Array
- C Program to Delete an Element in Array
- C Program to Find Unique Elements in an Array
- C Program to calculate the total number of Positive numbers, Negative numbers, and Zeros in an Array
- C Program to Count Even and Odd numbers in Array
- C Program to Delete Duplicate Elements from Sorted Array
- C Program to Reverse the Array Elements
- C Program to Reverse Array Elements using Recursion
- C Program to Sort Array Elements in Ascending order
- C Program to Sort Array in Ascending and Descending Order using QSort function
- C Program to Count Number of Unique Elements in Array
- C Program to Merge Two Arrays
1 Response
[…] C Program to Merge Two Sorted Array and Generate Sorted Array […]