C# program to merge two sorted arrays into one

CsharpProgrammingServer Side Programming

Set two arrays that you wish to merge −

int[] arr1 = new int[5] {
   5,
   15,
   25,
   30,
   47
};
int[] arr2 = new int[5] {
   55,
   60,
   76,
   83,
   95
};

Now take a third array that would merge both the above arrays −

int[] merged = new int[10];

The following is the code that merges two arrays into the third array in C# −

Example

 Live Demo

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      int i = 0;
      int j = 0;

      int[] arr1 = new int[5] {
         5,
         15,
         25,
         30,
         47
      };
      int[] arr2 = new int[5] {
         55,
         60,
         76,
         83,
         95
      };
      int[] merged = new int[10];
   
      for (i = 0, j = 0; i < 5; i++) {
         merged[j++] = arr1[i];
      }
      for (i = 0; i < 5; i++) {
         merged[j++] = arr2[i];
      }
      Console.WriteLine("Elements of merged array = ");
      for (i = 0; i < 10; i++) {
         Console.WriteLine("merged[" + (i) + "]: " + merged[i]);
      }
      Console.WriteLine();
   }
}

Output

Elements of merged array =
merged[0]: 5
merged[1]: 15
merged[2]: 25
merged[3]: 30
merged[4]: 47
merged[5]: 55
merged[6]: 60
merged[7]: 76
merged[8]: 83
merged[9]: 95
raja
Published on 21-Aug-2018 13:22:43
Advertisements