机试算法模板--堆

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100;
int heap[maxn]; //堆
int n;

//对heap数组在[low,high]范围内进行向下调整
void downAdjust(int low, int high) //low为欲调整结点的数组下标,high一般为堆的最后一个元素的数组下标
{
    int i = low;
    int j = i * 2;
    while (j <= high)
    {
        if (j + 1 <= high && heap[j + 1] > heap[j])
        {
            j = j + 1;
        }
        if (heap[i] < heap[j])
        {
            swap(heap[i], heap[j]);
            i = j;
            j = 2 * i;
        }
        else
        {
            break;
        }
    }
}

//建堆
void createHeap()
{
    for (int i = n / 2; i >= 1; i--) //从1开始存储堆
    {
        downAdjust(i, n);
    }
}

//删除堆顶元素
void deleteTop()
{
    heap[1] = heap[n--];
    downAdjust(1, n);
}

//对heap数组在[low,high]范围内进行向上调整
//low一般为1,high为欲调整结点的数组下标
void upAdjust(int low, int high)
{

    int i = high;
    int j = high / 2;
    while (j >= low)
    {
        if (heap[j] < heap[i])
        {
            swap(heap[i], heap[j]);
            i = j;
            j = i / 2;
        }
        else
        {
            break;
        }
    }
}

//添加元素x
void insert(int x)
{
    heap[++n] = x;
    upAdjust(1, n);
}

//堆排序
void heapSort()
{
    createHeap();
    for (int i = n; i > 1; i--) //倒着枚举,直到堆中只有一个元素
    {
        swap(heap[1], heap[i]);
        downAdjust(1, i - 1);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39504764/article/details/89555833