小根堆排序

2017-07-24 17:04:23

writer:pprp

参考书目:张新华的《算法竞赛宝典》

小根堆排序,使用数组模拟堆,时间复杂度为O(nlogn)

调整部分的程序比较难理解,有的地方还是不太清楚。

代码如下:

#include <iostream>

using namespace std;

const int N = 100000;

int a[N+1];

void adjust_down(int i,int m)
{
    int tmp;
    while(i*2 <= m)
    {
        i *= 2;
        if((i < m)&&(a[i+1]>a[i]))  //通过这个if判断左右哪个更大一点
            i++;
        if(a[i] > a[i/2]) // 如果max(左,右) > 父节点,那么交换
        {
            tmp = a[i];
            a[i] = a[i/2];
            a[i/2] = tmp;
        }
        else    //如果符合最小堆,那么不进行操作
        {
            break;
        }
    }
}

int main()
{

    int n;
    int i;

    cin >> n;
    // 从1开始用
    for(i = 1 ; i <= n ; i++)
    {
        cin >> a[i];
    }

    for(i = n/2; i>=1; i--)   // 只需从一半开始调整??
    {
        adjust_down(i,n);      //建立堆
    }

    for(i = n; i >= 2; i--)
    {
//        int tmp = a[i];
//        a[i] = a[1];
//        a[1] = tmp;
        a[i] = a[i]^a[1];
        a[1] = a[1]^a[i];
        a[i] = a[i]^a[1];
        adjust_down(1,i-1); //从1开始到i-1开始调整堆
    }

    for(i = 1 ; i <= n; i++)
        cout << a[i] << " ";
    cout << endl;

    return 0;
}
原文地址:https://www.cnblogs.com/pprp/p/7229949.html