Merge two sorted arrays in C#



To merge two sorted arrays, firstly set two sorted arrays −

int[] array1 = { 1, 2 }; int[] array2 = { 3, 4 };

Now, add it to a list and merge −

var list = new List<int>(); for (int i = 0; i < array1.Length; i++) {    list.Add(array1[i]);    list.Add(array2[i]); }

Use the ToArray() method to convert back into an array −

int[] array3 = list.ToArray();

The following is the complete code −

Example

 Live Demo

using System; using System.Collections.Generic; public class Program {    public static void Main() {       int[] array1 = { 1, 2 };       int[] array2 = { 3, 4 };       var list = new List<int>();       for (int i = 0; i < array1.Length; i++) {          list.Add(array1[i]);          list.Add(array2[i]);       }       int[] array3 = list.ToArray();       foreach(int res in array3) {          Console.WriteLine(res);       }    } }

Output

1 3 2 4
Updated on: 2020-06-22T13:09:18+05:30

861 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements