堆排序

void adjust(int i, int nLen)
{
    int j = ((nLen - 1) - 1) / 2;
    while (j >= i)
    {
        if (2 * j + 1 > nLen - 1)
        {
            break;
        }

        if (2 * j + 2 > nLen - 1)
        {
            if (g_szArray[j] < g_szArray[2 * j + 1])
            {
                int nTmp = g_szArray[j];
                g_szArray[j] = g_szArray[2 * j + 1];
                g_szArray[2 * j + 1] = nTmp;
            }
        }
        else
        {
            int *pMax = 0;
            if (g_szArray[2 * j + 1] > g_szArray[2 * j + 2])
            {
                pMax = &g_szArray[2 * j + 1];
            }
            else
            {
                pMax = &g_szArray[2 * j + 2];
            }

            if (g_szArray[j] < *pMax)
            {
                int nTmp = g_szArray[j];
                g_szArray[j] = *pMax;
                *pMax = nTmp;
            }
        }

        j--;
    }
}

void main()
{
    int nLen = sizeof(g_szArray) / sizeof(g_szArray[0]);
    adjust(0, nLen);

    int nCnt = nLen;
    for (int i = 0; i <= nLen - 1; i++)
    {
        int nTmp = g_szArray[0];
        g_szArray[0] = g_szArray[nLen - 1 - i];
        g_szArray[nLen - 1 - i] = nTmp;
        adjust(0, --nCnt);
    }

    for (int i = 0; i < nLen; i++)
    {
        printf("%d ", g_szArray[i]);
    }
    printf("\n");
    system("pause");
}

 

posted @ 2019-11-25 11:37  _No.47  阅读(207)  评论(0编辑  收藏  举报