In this C# prgramming example, we will learn how we can merge two sorted arrays into one in the C# program.
Before going to the problem-solution first we have to know the basic things that what is Array, Sort, and Merge mean.
Array:
The array is a collection of similar data elements stored in contiguous memory locations. It is a simple data structure where each data element can be accessed directly by using only its index number.
Sort:
Sorting means arranging the data in an increasing or decreasing order according to some linear relationship among the data items.
Merge:
Merging is the practice of taking two or more groups of data and combining them into a single group.
How to Merge Two Sorted Arrays in C#
You always wanted to know how to merge two sorted arrays in O(n) time complexity. It’s very simple if you know Merge Sort. Merge Sort works on the divide and conquer technique or rule, Merge Sort divides an array into the smallest chunks and starts merging them. By the time of merging, it takes one element from each of the arrays then compares it and places a smaller one on the output array.
Here we will use the same technique to merge two sorted arrays. Since we already have sorted arrays we don’t need to divide them but we will compare both arrays elements for deciding which element will have to place first.
C# program to merge two sorted arrays
using System; class MergeArray { public static void mergeArrays(int[] arr1, int[] arr2,int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } while (i < n1) arr3[k++] = arr1[i++]; while (j < n2) arr3[k++] = arr2[j++]; } public static void Main() { int[] arr1 = {1, 3, 5, 7}; int n1 = arr1.Length; int[] arr2 = {2, 4, 6, 8}; int n2 = arr2.Length; int[] arr3 = new int[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); Console.Write("Array after merging\n"); for (int i = 0; i < n1 + n2; i++) Console.Write(arr3[i] + " "); } }
Output:
Array after merging 1 2 3 4 5 6 7 8
Here we have to Merge arr1[0..n1-1] and arr2[0..n2-1] into arr3[0..n1+n2-1] first we will traverse both array. By checking with if condition if the current element of the first array is smaller than a current element of the second array, If this condition is true then store the first array element and increment the first array index. Otherwise do the same with the second array. Traverse both arrays with the same approach Store remaining elements of the first array.
So by this C# program, you can easily merge two sorted arrays.