#include<iostream>
using namespace std;
//大根堆
class MyHeap{
private:
int m_heapSize;
int m_maxSize;
int * m_arr;
public:
MyHeap(int limit)
{
m_arr = new int[limit];
this->m_maxSize = limit;
m_heapSize = 0;
}
~MyHeap()
{
cout<<"~MyHeap"<<endl;
delete []m_arr;
m_arr = nullptr;
}
bool isEmpty()
{
return this->m_heapSize == 0;
}
bool isFull()
{
return this->m_heapSize == m_maxSize;
}
void push(int val)
{
if(isFull())
{
cout<<"大根堆已满,无法再push元素"<<endl;
return;
}
m_arr[m_heapSize++]=val;
heapInsert();
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
//从最后一个位置的元素往上heapInsert
void heapInsert()
{
int index = m_heapSize - 1;
int fa = (index-1)/2;
while(m_arr[index] > m_arr[fa])
{
swap(m_arr[index], m_arr[fa]);
index = fa;
fa = (index-1)/2;
}
}
int pop()
{
int val = m_arr[0];
swap(m_arr[0], m_arr[--m_heapSize]);
heapify();
return val;
}
//将移上来的最后一个数从0开始往下heapify
void heapify()
{
int index = 0;
int left = 2*index + 1;
while(left < m_heapSize)
{
//找到左右孩子中较大的那个孩子的坐标
int maxIndex = left + 1 < m_heapSize && m_arr[left+1] > m_arr[left]? left+1:left;
if(m_arr[index] > m_arr[maxIndex])
{
break;
}
swap(m_arr[index], m_arr[maxIndex]);
index = maxIndex;
left = 2 * index +1;
}
}
int top()
{
if(!this->isEmpty())
{
return this->m_arr[0];
}
return -1;
}
};
int main()
{
MyHeap heap(5);
heap.push(1);
cout<<heap.top()<<endl;
heap.push(3);
cout<<heap.top()<<endl;
heap.push(9);
cout<<heap.top()<<endl;
heap.push(6);
cout<<heap.top()<<endl;
heap.push(3);
cout<<heap.top()<<endl;
heap.pop();
cout<<heap.top()<<endl;
system("pause");
return 0;
}
手写堆(大根堆)
于 2024-04-15 23:44:33 首次发布