Hard csharp

Merge two sorted arrays

Problem

Merge {1,3,5} and {2,4,6} into sorted output.

Hints
  • Compare a[i] and b[j], append smaller, advance pointer.

Your practice code

Ready — edit the code above and click Run.

Solution

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] a = { 1, 3, 5 }, b = { 2, 4, 6 };
        var result = new List<int>();
        int i = 0, j = 0;
        while (i < a.Length && j < b.Length)
            result.Add(a[i] <= b[j] ? a[i++] : b[j++]);
        while (i < a.Length) result.Add(a[i++]);
        while (j < b.Length) result.Add(b[j++]);
        Console.WriteLine(string.Join(", ", result));
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Two-pointer merge—building block of merge sort; often asked in .NET interviews.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details