Quick actions

cmd+k|ctrl+k

Navigation

Languages

Merge 2 Sorted Lists in C#

Snippet info

Language

Csharp

Visibility

public

Author

patrykstachowiak

Created

2025-03-06T21:19:55.036927Z

Updated

2025-03-06T21:41:53.558217Z

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;
    }
}
INFO