Merge Sorted Arrays

Run Settings
LanguageC#
Language Version
Run Command
using System; using System.Collections.Generic; using System.Linq; class MainClass { static void Main() { //Merge Sorted Array //Takes two arrays //Merge arrays keeping order int?[] array2 = new int?[4]{0,3,4,35}; int?[] array1 = new int?[5]{4,6,30,40,45}; var result = MergeSorted(array1, array2); Console.WriteLine(string.Join(",", result)); } public static int?[] MergeSorted(int?[] array1, int?[] array2) { int?[] mergedArray = new int? [array1.Length + array2.Length]; int mergedArrayIndex = 0; //Arrays are sorted //i = 1, j = 4 //[4,6,30,40,45] [0,3,4,5] //[0,3,4,4,5,6,30,40,45] int? array1Item = array1.ElementAtOrDefault(0); int? array2Item = array2.ElementAtOrDefault(0); int i = 0; int j = 0; while(array1Item != null || array2Item != null) { if (array2Item == null || array1Item < array2Item) { mergedArray[mergedArrayIndex++] = array1Item; i++; } else { mergedArray[mergedArrayIndex++] = array2Item; j++; } array1Item = array1.ElementAtOrDefault(i); array2Item = array2.ElementAtOrDefault(j); } return mergedArray; } public static int [] ShiftElementsRight(int [] objs, int index) { for (int i = objs.Length -1; i > index; i--) { objs[i] = objs[i - 1]; } return objs; } }
Editor Settings
Theme
Key bindings
Full width
Lines