所以我需要创建一个优先级队列类,其中包含函数Add(),Top()和Pop()以及成员变量Heap。一般来说,我如何使用堆类(下面)来实现上述功能?我正在创建一个100个整数的数组,范围从1-100。
#pragma once
#include <iostream>
#include <vector>
using namespace std;
class Heap
{
private:
bool minHeap;
int size;
int end;
int* arr;
public:
Heap(bool minHeap = true)
{
this->minHeap = minHeap;
end = 0;
size = 50;
arr = new int[size];
}
void Resize(int newSize)
{
int* temp = new int[newSize];
delete[] arr;
arr = temp;
size = newSize;
}
void HeapSort(vector<int> &vec)
{
Resize(vec.size());
for (int i = 0; i < vec.size(); i++)
{
arr[i] = vec[i];
end++;
}
BuildHeap();
for (int i = 0; i < vec.size(); i++)
{
vec[i] = arr[0];
int temp = arr[0];
arr[0] = arr[--end];
arr[end] = temp;
Heapify(0);
}
}
void Heapify(int index)
{
int leftChild = LeftChild(index);
int rightChild = RightChild(index);
int target = -1;
if (minHeap)
{
if (leftChild < end && arr[index] > arr[leftChild])
target = leftChild;
else
target = index;
if (rightChild < end && arr[target] > arr[rightChild])
target = rightChild;
}
else//Max Heap
{
if (leftChild < end && arr[index] < arr[leftChild])
target = leftChild;
else
target = index;
if (rightChild < end && arr[target] < arr[rightChild])
target = rightChild;
}
if (target != index)
{
int temp = arr[index];
arr[index] = arr[target];
arr[target] = temp;
Heapify(target);
}
}
void BuildHeap()
{
for (int i = (end - 1) / 2; i >= 0; i--)
Heapify(i);
}
void PrintHeap()
{
for (int i = 0; i < end && i < 50; i++)
cout << arr[i] << " ";
}
void Add(int val)
{
if (end == size)
Grow();
arr[end++] = val;
}
void Grow()
{
size *= 2;
int* temp = new int[size];
for (int i = 0; i < end; i++)
temp[i] = arr[i];
delete[] arr;
arr = temp;
}
~Heap()
{
delete[] arr;
}
int Parent(int index)
{
return (index - 1) / 2;
}
int LeftChild(int index)
{
return 2 * index + 1;
}
int RightChild(int index)
{
return 2 * index + 2;
}
};