优先队列
优先队列的本质依然是最大堆,只是对最大堆的操作不同
源码:(本源码仅对《算法导论》中函数伪代码进行具体实现,正确性未验证)
#include<iostream>
using namespace std;
int heapsize = 0;
int max_limitation;
const int ERROR_CODE = -1;
int maxium(int *arr);
int extract_max(int *arr);
void increase_key(int *arr, int node_index, int value);
void insert(int *arr, int new_node_value);
void maintain_max_heap(int *arr, int node_index, int heapsize);
int main()
{
}
int maxium(int *arr)//返回最大值
{
return arr[0];
}
int extract_max(int *arr)//删除最大值并将其返回
{
int temp;
if (heapsize == 0)
{
cout << "error,heap underflow";
return ERROR_CODE;
}
//将尾部值和最大值互换,并将堆大小减一,维护堆
else
{
temp = arr[0];
arr[0] = arr[heapsize - 1];
arr[heapsize - 1] = temp;
heapsize = heapsize - 1;
maintain_max_heap(arr, 0, heapsize);
return temp;
}
}
void increase_key(int *arr, int node_index, int value)//增加键值
{
if (arr[node_index] > value)
{
cout << "sorry,new key is smaller than current key" << endl;
}
int parent_index = (node_index + 1) / 2 - 1;
int temp;
while (node_index>0 && arr[node_index]>arr[parent_index])
{
temp = arr[parent_index];
arr[parent_index] = arr[node_index];
arr[node_index] = temp;
node_index = parent_index;
parent_index = (node_index + 1) / 2 - 1;
}
}
void insert(int *arr, int new_node_value)//通过在末尾增加一个节点并设置为最小值,再对其调用increase_key增加值到期望的值value
{
if (heapsize == max_limitation)
cout << "out of max_limitation" << endl;
else
{
heapsize = heapsize + 1;
arr[heapsize-1] = INT_MIN;
increase_key(arr, heapsize, new_node_value);
}
}
//维护最大堆
void maintain_max_heap(int *arr, int node_index, int heapsize)
{
int left_node_index = (node_index + 1) * 2 - 1;
int right_node_index = (node_index + 1) * 2;
int largest_node_index;
//选择左子节点和右子节点比该节点大且为最大值的节点交换值
if (left_node_index<heapsize&&arr[left_node_index]>arr[node_index])
largest_node_index = left_node_index;
else
largest_node_index = node_index;
if (right_node_index<heapsize&&arr[right_node_index]>arr[largest_node_index])
largest_node_index = right_node_index;
//若有交换则递归调用maintain_max_heap函数
int temp;
if (largest_node_index != node_index)
{
temp = arr[node_index];
arr[node_index] = arr[largest_node_index];
arr[largest_node_index] = temp;
maintain_max_heap(arr, largest_node_index, heapsize);
}
}