对于使用堆,其实质上是对完全二叉树进行操作,在理论上看成是树形结构,但在实际代码中,使用数组在进行相关的操作。由于堆会有动态增加元素的功能,所以最好使用容器,不要使用数组,现将以前代码都换成容器,但切记,一定要引用,因为如果是数组,传递给函数的是数组指针,可以直接修改值,而容器是对象,不能直接修改,所以要用引用。
其所有函数的相关代码如下:
//建堆
void Insert::BuileMaxHeap(vector<int> &A,int total)
{
int roots=total/2-1;//建堆时,把数组元素后一半的视为完全二叉树即堆的叶子.
for(;roots>=0;--roots)
{
MaxHeapIFY(A,roots,total);
}
}
void Insert::MaxHeapIFY(vector<int> &A,int local,int total)//堆维护,最重要
{
int left_child=(local+1)*2-1;//因为是从0开始计数,所以计算公式有2i变为此公式
int right_child=(local+1)*2;
int largest=local;
if(left_child<total && A[local] < A[left_child])
{
largest=left_child;
}
if(right_child<total && A[largest] < A[right_child])
{
largest=right_child;
}
if(largest!=local)
{
int temp=A[local];
A[local]=A[largest];
A[largest]=temp;
MaxHeapIFY(A,largest,total);
}
}
void Insert::HeapSort(vector<int> &A,int total)//堆排序从小到大
{
int temp=0;
for(int i=total-1;i>=1;--i)
{
temp=A[i];
A[i]=A[0];
A[0]=temp;
--total;
MaxHeapIFY(A,0,total);
}
}
//一下是最大优先队列的函数,针对于堆
int Insert::MaxKeyValue(vector<int> &A)//对于堆而言
{
return A[0];
}
void Insert:: HeapIncreseKey(vector<int> &A,int value,int key)
{
if(key<A[value])
{
cout<<"this key is lower than themself!";
return;
}
A[value]=key;
while(value>0 && A[value/2] < A[value])//父节点<子节点
{
int temp=0;
temp=A[value/2];
A[value/2]=A[value];
A[value]=temp;
value/=2;//value始终位子节点
}
}
void Insert::MaxHeapInsert(vector<int> &coll,int key)
{
coll.push_back(-65535);
int temp=coll.size();
HeapIncreseKey(coll,temp-1,key);
}