代码改变世界

2个有序数组,归并重拍

2024-08-20 14:51  qgbo  阅读(3)  评论(0编辑  收藏  举报
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] + ", ");
    }
}