最大堆实现优先队列
头文件
#include "heap_sort.h"
#include "stdexcept"
#include <iostream>
class MaxHeapPriorityQueue {
public:
int heap_size;
private:
int capacity;
int *array;
void increase_key(int key,int index);
public:
void insert(int key);
int maximum();
int extract_max();
void heap_delete(int index);
const int* get_array();
MaxHeapPriorityQueue(int capacity = 50);
MaxHeapPriorityQueue(const int *array,const int length);
virtual ~MaxHeapPriorityQueue();
};
cpp文件
#include "MaxHeapPriorityQueue.h"
MaxHeapPriorityQueue::MaxHeapPriorityQueue(int capacity):capacity(capacity)
{
array = new int [capacity];
heap_size = 0;
}
MaxHeapPriorityQueue::MaxHeapPriorityQueue(const int *array,const int length)
{
capacity = length;
this->array = new int [capacity];
heap_size = capacity;
for (int i = 0; i < heap_size; ++i) {
this->array[i] = array[i];
}
build_heap(this->array,heap_size);
}
void MaxHeapPriorityQueue::increase_key(int key,int index){
if(index >= heap_size || key < array[index])
{
perror("new key error");
return;
}
array[index] = key;
while (index>0 && array[parent(index)] < key)
{
array[index] = array[parent(index)];
array[parent(index)] = key;
index = parent(index);
}
}
void MaxHeapPriorityQueue::insert(int key){
heap_size ++;
if(heap_size>capacity)
{
int *temp_array = new int [capacity*2];
for (int i = 0; i < heap_size; ++i) {
temp_array[i] = array[i];
}
delete[] array;
array = temp_array;
capacity *= 2;
}
array[heap_size - 1] = INT_MIN;
increase_key(key,heap_size-1);
}
int MaxHeapPriorityQueue::maximum(){
return array[0];
}
int MaxHeapPriorityQueue::extract_max(){
int max = array[0];
array[0] = array[heap_size-1];
heap_size --;
max_heapify(array,heap_size,0);
return max;
}
void MaxHeapPriorityQueue::heap_delete(int index){
if(index>=heap_size || index < 0 || heap_size<=0)
{
perror("index overflow");
return;
}
if(array[index] > array[heap_size-1])
{
array[index] = array[heap_size-1];
max_heapify(array,heap_size-1,index);
}
else
{
increase_key(array[heap_size-1],index);
}
heap_size --;
}
const int* MaxHeapPriorityQueue::get_array(){
return array;
}
MaxHeapPriorityQueue::~MaxHeapPriorityQueue()
{
if(array!= nullptr)
delete [] array;
}
内置的堆排序代码链接:堆排序