C# program to merge two sorted arrays into one
To merge two sorted arrays into one sorted array in C#, you can use a merging algorithm. Here's an example program that merges two sorted arrays into a single sorted array:
using System;
public class Program {
public static void Main(string[] args) {
int[] arr1 = { 1, 3, 5, 7, 9 };
int[] arr2 = { 2, 4, 6, 8, 10 };
int[] mergedArray = MergeSortedArrays(arr1, arr2);
Console.WriteLine("Merged array:");
foreach (int num in mergedArray) {
Console.Write(num + " ");
}
}
public static int[] MergeSortedArrays(int[] arr1, int[] arr2) {
int[] mergedArray = new int[arr1.Length + arr2.Length];
int i = 0, j = 0, k = 0;
while (i < arr1.Length && j < arr2.Length) {
if (arr1[i] < arr2[j]) {
mergedArray[k++] = arr1[i++];
}
else {
mergedArray[k++] = arr2[j++];
}
}
while (i < arr1.Length) {
mergedArray[k++] = arr1[i++];
}
while (j < arr2.Length) {
mergedArray[k++] = arr2[j++];
}
return mergedArray;
}
}
In this program, we have two sorted arrays, arr1 and arr2, containing integers. We use the MergeSortedArrays method to merge the two sorted arrays into a single sorted array. The merging algorithm compares the elements of both arrays and fills the merged array with the smaller element at each step.
The program outputs the merged array:
Merged array:
1 2 3 4 5 6 7 8 9 10
In this case, arr1 is { 1, 3, 5, 7, 9 } and arr2 is { 2, 4, 6, 8, 10 }. The program merges the two arrays into a single sorted array where each element is in ascending order.