堆排序

时间:2019-11-25
本文章向大家介绍堆排序,主要包括堆排序使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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");
}

原文地址:https://www.cnblogs.com/predator-wang/p/11926735.html