堆排序代码:
//头文件省略
函数:heapify 维护堆
void heapify(vector<int>& in, int bottom, int top) // bottom 其实是数组的size 即堆的底部。top 就是当前堆的顶部。
{
int largest = top; //假设当前最大值就是当前堆的父节点(下标)
int lson = top*2 + 1;//根据堆的性质计算出左子节点的下标
int rson = top*2 + 2;//根据堆的性质计算出右子节点的下标
if(lson < bottom && in[largest] < in[lson]) // 如果计算出来的左孩子已经超出了底部(即不存在)就不成立 ; 比较顶部和孩子的大 //小, 重新记录最大值
{
largest = lson;
}
if(rson < bottom && in[largest] < in[rson])// 同理
{
largest = rson;
}
if(largest != top)//在上述过程中,最大值发生了变化,那么维护堆(将大的(应该在顶部的)数据放到顶部)
{
swap(in[largest],in[top]);
heapify(in,bottom,largest);
}
};
void heap_sort(vector<int>& in,int bottom)
{
for(int i = bottom/2;i>=0;i--)
{
heapify(in,bottom,i);
}
for(int i = bottom - 1;i>0;i--)
{
swap(in[i],in[0]);
heapify(in,i,0);
}
};
int main()
{
return 0;
}
维护最大堆(大根堆)
判断结点的左右子结点,寻找最大值,使结点上浮
然后递归往修改了的子结点方向深处走,直到叶子结点(叶子结点是利用数组的存储方式判定的)
堆排序
将最大值放到数组的最后面然后重新从堆顶维护整个大根堆
本文来自博客园,作者:快乐过了阈值,转载请注明原文链接:https://www.cnblogs.com/black-worrior-2000/p/16588192.html
墨愁前路无知己,天下谁人不识君。
浙公网安备 33010602011771号