Medium csharp

DS — merge two sorted arrays #16

Problem

Merge [1,3,5] and [2,4,6]; print merged.

Hints
  • Compare a[i] and b[j]

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;

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

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

Explanation

Two-pointer merge — merge sort building block.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

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