《数据结构:邓俊辉版》——并归排序

void MergeSort(int low, int high)
{
    int mid = (low + high) / 2;
    if (high - low < 1)
    {
        return;
    }
    MergeSort(low, mid);
    MergeSort(mid + 1, high);
    Merge(low, mid, high);
}

void Merge(int low, int mid, int high)
{
    int* A = g_szArray + low;
    int llen = mid - low + 1;
    int* B = new int[llen];
    for (int i = 0; i < llen; i++)
    {
        B[i] = g_szArray[low + i];
    }

    int hlen = high - mid;
    int* C = g_szArray + mid + 1;
    for (int i = 0, j = 0, k = 0; (j < llen) || (k < hlen);)
    {
        if ((j < llen) && (!(k < hlen) || (B[j] <= C[k])))
        {
            A[i++] = B[j++];
        }
        if ((k < hlen) && (!(j < llen) || (C[k] < B[j])))
        {
            A[i++] = C[k++];
        }
    }

    delete []B;
}

相关推荐