2個有序陣列,歸併重拍

qgbo發表於2024-08-20
public static void merge(int[] a, int[] b)
{ 
    var pa= a.Length-1;
    var pb = b.Length-1;
 
 
    var c = new int[b.Length];
    var pc = b.Length-1;
 
    while (pc >= 0)
    {
        if (a[pa] > b[pb])
        {
            c[pc] = a[pa];
            pa--;
        }
        else
        {
            c[pc] = b[pb];
            pb--;
        }
        pc--;
    }
 
    while (pb >= 0)
    {
        if (a[pa] > b[pb])
        {
            a[pa + pb + 1] = a[pa];
            pa--;
        }
        else
        {
            a[pa + pb + 1] = b[pb];
            pb--;
        }
    }
    b = c;
 
    for (int i = 0; i < a.Length; i++) {
        Console.Write(a[i]+ ", ");
    }
 
    Console.WriteLine();
 
    for (int i = 0; i < b.Length; i++)
    {
        Console.Write(b[i] + ", ");
    }
}

相關文章