Merge two sorted arrays in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 31-Aug-2018 16:40:50
Advertisements