#include <iostream>
#include <vector>
class UnderflowException { };
using namespace std;
template<typename Comparable>
class minHeap
{
public:
explicit minHeap(int capacity=100)
:array(capacity+1),currentSize(0)
{}
explicit minHeap(const vector<Comparable> &items)
:array(items.size()+10),currentSize(items.size())
{
for(int i=0;i<items.size();++i)
array[i+1]=items[i];
buildHeap();
}
bool isEmpty() const
{
return currentSize==0;
}
int currSize() const
{
return currentSize;
}
void print()
{
for(int i=1;i<=currentSize;++i)
cout<<array[i]<<" ";
cout<<endl;
}
//return the min
const Comparable& findMin() const
{
if (isEmpty())
throw UnderflowException{ };
return array[1];
}
//decrease the value in position i to key
int decreaseKey(int i,const Comparable &key)
{
if(key>=array[i])
{
cout<<"the key is greater than current key,can not change"<<endl;
return -1;
}
array[i]=key;
while(i>1&&array[i/2]>array[i])
{
std::swap(array[i/2],array[i]);
i=i/2;
}
return 0;
}
//Insert the x into the heap
void insert(const Comparable &x)
{
if (currentSize==array.size()-1)
array.resize(array.size()*2);
int hole=++currentSize;
array[hole]=INT_MAX;
decreaseKey(hole,x);
}
//delete the minMum and return it
int deleteMin()
{
if(isEmpty())
throw UnderflowException{ };
Comparable tmp=array[1];
std::swap(array[1],array[currentSize--]);
minHeapIfy(1);
return tmp;
}
//minHeapSort
void minHeapSort(vector<Comparable> &vec)
{
while(currentSize)
{
Comparable tmp=deleteMin();
vec.push_back(tmp);
}
}
private:
int currentSize;
vector<Comparable> array;
void buildHeap()
{
for(int i=currentSize/2;i>0;--i)
minHeapIfy(i);
}
void minHeapIfy(int i)
{
int child;
Comparable tmp=std::move(array[i]);
for(;i*2<=currentSize;i=child)
{
child=i*2;
if(child!=currentSize&&array[child]>array[child+1])
++child;
if(array[child]<tmp)
array[i]=std::move(array[child]);
else
break;
}
array[i]=std::move(tmp);
}
};
int main()
{
cout<<INT_MAX<<endl;
vector<int> vec{9,8,7,6,5};
minHeap<int> heap{vec};
heap.print();
cout<<heap.currSize()<<endl;
heap.insert(1);
cout<<heap.currSize()<<endl;
heap.print();
vector<int> vec2;
heap.minHeapSort(vec2);
for(auto v:vec2)
cout<<v<<" ";
cout<<endl;
}
算法导论—最小堆
最新推荐文章于 2018-10-08 13:39:16 发布