Merge 2 Sorted Lists in C#

Run Settings
LanguageC#
Language Version
Run Command
using System; using System.Collections.Generic; using System.Linq; class MainClass { static void Main() { Console.WriteLine("Hello World!"); int[] firstCollection = { 0, 3, 4, 31 }; int[] secondCollection = { 4, 6, 30 }; List<int> merged = MergeArray(firstCollection.ToList(), secondCollection.ToList()); Console.WriteLine(string.Join(", ", merged)); // Output: 0, 3, 4, 4, 6, 30, 31 } public static List<int> MergeArray(List<int> firstArray, List<int> secondArray) { List<int> mergedArray = new List<int>(); int firstIndex = 0; int secondIndex = 0; int firstItem = firstArray[firstIndex]; int secondItem = secondArray[secondIndex]; while (firstIndex < firstArray.Count || secondIndex < secondArray.Count) { if (secondItem == 0 || firstItem < secondItem) { mergedArray.Add(firstItem); firstItem = firstArray[firstIndex]; firstIndex++; Console.WriteLine("Adding first: " + firstItem); } else { mergedArray.Add(secondItem); secondItem = secondArray[secondIndex]; secondIndex++; Console.WriteLine("Adding second: " + secondItem); } } return mergedArray; } }
Editor Settings
Theme
Key bindings
Full width
Lines