#include <iostream>
using namespace std;
#define parent ((pos-1)/2)
#define left (2*pos+1)
#define right (left+1)
int MAX_HEAPIFY(int *A, int pos, int &heapsize) // 维护堆的属性 保持父节点的值大于子节点;
{
int largest = pos;
if (left < heapsize && A[left] > A[pos])
{
largest = left;
}
else
{
largest = pos;
}
if (right < heapsize && A[right] > A[largest])
{
largest = right;
}
if (largest != pos)
{
swap(A[pos], A[largest]);
MAX_HEAPIFY(A, largest, heapsize);
}
return 0;
}
int BUILD_HEAP(int *A, int &heapsize) //建立最大堆 ;
{
for (int i = (heapsize/2)-1; i >= 0;--i)
{
MAX_HEAPIFY(A, i, heapsize);
}
return 0;
}
int HEAPSORT(int *A, int &heapsize) // 堆排序;
{
BUILD_HEAP(A, heapsize);
for (int i = heapsize - 1; i >= 1; --i)
{
swap(A[i], A[0]);
--heapsize;
MAX_HEAPIFY(A, 0, heapsize);
}
return 0;
}
int HEAP_MAXIMUM(int *A) // 返回堆中最大的元素值;
{
return A[0];
}
int HEAP_EXTRACT_MAX(int *A, int &heapsize) // 去掉并返回堆中最大元素;
{
if (heapsize < 1)
{
cerr << "heap underflow";
}
int max = A[0];
swap(A[0], A[heapsize-1]);
--heapsize;
MAX_HEAPIFY(A, 0, heapsize);
return max;
}
int HEAP_INCREASE_KEY(int *A, int pos, int key) //将元素的值增加到k 假设k>=x;
{
if (key < A[pos])
{
cerr << "no key is smaller than current key";
}
A[pos] = key;
while (pos >= 1 && A[parent] < A[pos])
{
swap(A[parent], A[pos]);
pos = parent;
}
return 0;
}
int MAX_HEAP_INSERT(int *A, int key, int &heapsize) // 把新元素key插入到堆中合适的位置;
{
++heapsize;
A[heapsize-1] = -100000;
HEAP_INCREASE_KEY(A, heapsize-1, key);
return 0;
}
int print(int *A, int &heapsize) //输出函数;
{
for (int i = 0; i < heapsize; ++i)
{
cout << A[i] << " ";
}
cout << endl;
return 0;
}
int main()
{
int A[100] = {1,2,3,4,5,6,7,8,9};
int heapsize = 9;
BUILD_HEAP(A,heapsize);
cout << "建堆后" << endl;
print(A, heapsize);
cout << "最大元素值 :" << HEAP_MAXIMUM(A) << endl;
cout << "使用 HEAP_EXTRACT_MAX 后 :" << endl;
HEAP_EXTRACT_MAX(A, heapsize);
print(A, heapsize);
cout << "使用了 HEAP_INCREASE_KEY 后 : " << endl;
HEAP_INCREASE_KEY(A, 2, 10);
print(A, heapsize);
cout << "使用了 MAX_HEAP_INSERT " << endl;
MAX_HEAP_INSERT(A, 11, heapsize);
print(A, heapsize);
return 0;
}
最大优先队列
最新推荐文章于 2022-03-29 08:49:14 发布