Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

รวมอาร์เรย์ที่เรียงลำดับแล้วสองอาร์เรย์เป็น List ใน C# (Interleaving)

บทความนี้สาธิตการรวมอาร์เรย์สองอาร์เรย์โดยการ Interleave (สลับกัน) ไม่ใช่ Merge แบบเรียงลำดับ คล้ายกับการ Shuffle การ์ดแบบ Perfect Shuffle

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        int[] array1 = { 56, 70, 77 };
        int[] array2 = { 80, 99, 180 };

        var list = new List();

        // สมมติขนาดเท่ากัน
        for (int i = 0; i < array1.Length; i++)
        {
            list.Add(array1[i]);
            list.Add(array2[i]);
        }

        int[] merged = list.ToArray();

        foreach (int val in merged)
            Console.WriteLine(val);
    }
}

ผลลัพธ์

56
80
70
99
77
180

Generic Interleave Method (รองรับขนาดต่างกัน)

public static List Interleave(IEnumerable first, IEnumerable second)
{
    var result = new List();
    using var enum1 = first.GetEnumerator();
    using var enum2 = second.GetEnumerator();

    bool has1, has2;
    while ((has1 = enum1.MoveNext()) | (has2 = enum2.MoveNext()))
    {
        if (has1) result.Add(enum1.Current);
        if (has2) result.Add(enum2.Current);
    }
    return result;
}

LINQ Version (Deferred Execution)

public static IEnumerable InterleaveLazy(IEnumerable first, IEnumerable second)
{
    using var e1 = first.GetEnumerator();
    using var e2 = second.GetEnumerator();

    while (e1.MoveNext() || e2.MoveNext())
    {
        if (e1.Current != null) yield return e1.Current;
        if (e2.Current != null) yield return e2.Current;
    }
}

Zip + SelectMany Alternative

// สำหรับขนาดเท่ากันเท่านั้น
var interleaved = array1.Zip(array2, (a, b) => new[] { a, b })
                       .SelectMany(x => x);

กรณีใช้งานจริง

  • Audio Processing: Interleave Stereo Channels (Left, Right, Left, Right...)
  • Graphics: Interleave Vertex Attributes (Position, Normal, UV...)
  • Network Protocol: Multiplexing Multiple Streams
  • Test Data: สร้างข้อมูลทดสอบแบบ Alternating Pattern

⚠️ หมายเหตุสำคัญ

นี่ ไม่ใช่ Merge Sorted Arrays แบบคลาสสิก (Two-Pointer Technique) หากต้องการผลลัพธ์ที่เรียงลำดับ ต้องใช้ Merge Algorithm แทน