C Heapsort-向下渗透/向下移位与Heapify操作之间的区别/关系是什么?
降渗/降档和Heapify操作之间的区别是什么 这是我在C中的下移函数。我已经用这段代码实现了HeapsortC Heapsort-向下渗透/向下移位与Heapify操作之间的区别/关系是什么?,c,heapsort,C,Heapsort,降渗/降档和Heapify操作之间的区别是什么 这是我在C中的下移函数。我已经用这段代码实现了Heapsort void IterativeShiftDown(int i) { int leftOrRightChildIndex = EMPTY; int currentIndex = i; int currentElement = EMPTY; int childElement = EMPTY; while(HasAnyChild(currentI
void IterativeShiftDown(int i)
{
int leftOrRightChildIndex = EMPTY;
int currentIndex = i;
int currentElement = EMPTY;
int childElement = EMPTY;
while(HasAnyChild(currentIndex))
{
if(HasBothChild(currentIndex))
{
if(GetLeftChildElement(currentIndex) > GetRightChildElement(currentIndex))
{
leftOrRightChildIndex = GetLeftChildIndex(currentIndex);
}
else
{
leftOrRightChildIndex = GetRightChildIndex(currentIndex);
}
}
else if(HasLeftChild(currentIndex))
{
leftOrRightChildIndex = GetLeftChildIndex(currentIndex);
}
currentElement = GetElement(currentIndex);
childElement = GetElement(leftOrRightChildIndex);
if(currentElement < childElement)
{
SwapElements(currentIndex, leftOrRightChildIndex);
}
currentIndex = leftOrRightChildIndex;
}
}
void IterativeShiftDown(int i)
{
int leftOrRightChildIndex=空;
int currentIndex=i;
int currentElement=空;
int childElement=空;
while(HasAnyChild(currentIndex))
{
if(HasBothChild(currentIndex))
{
if(GetLeftChildElement(currentIndex)>GetRightChildElement(currentIndex))
{
leftOrRightChildIndex=GetLeftChildIndex(currentIndex);
}
其他的
{
leftOrRightChildIndex=GetRightChildIndex(currentIndex);
}
}
else if(HasLeftChild(currentIndex))
{
leftOrRightChildIndex=GetLeftChildIndex(currentIndex);
}
currentElement=GetElement(currentIndex);
childElement=GetElement(leftOrRightChildIndex);
if(currentElement
我可以使用此代码创建Heapify()函数吗
如果是,如何进行
此外,使用Heapify实现Heapsort的算法是什么?是的,基本上可以通过向下移动所有项来实现。来自维基百科:
function heapify(a, count) is
(start is assigned the index in a of the last parent node)
start := (count - 1) / 2
while start ≥ 0 do
(sift down the node at index start to the proper place such that all nodes below
the start index are in heap order)
siftDown(a, start, count-1)
start := start - 1
(after sifting down the root all nodes/elements are in heap order)
向下移位通常是将项插入现有堆中的操作 heapify通常是从无序数据创建堆的操作 要扩展perreal提供的函数
从中间开始,因为数组中实现堆的属性。堆中索引N中的每个子元素都是N*2或N*2+1,因此您知道最后1/2的元素没有子元素。此外,堆中节点的子节点与父节点有关系(始终较大或较小或其他),但彼此之间没有关系-因此叶子节点永远不需要交换
因此,它从中间开始,根据需要对每个元素进行起泡/筛选 有时候,堆是很好的。具体地说,如果您接收输入的方式是在检索数据(异步磁盘读取/db-get)时可以免费执行一些CPU工作,那么您几乎可以免费增量地构建堆 同样,一旦您有了数据,如果您想要填充一些UI或者能够以某种零碎的方式反馈结果,您就可以立即获得初始结果,并且检索每个元素的成本很低 它不是世界上分类数据最快的;但就我而言,这是在算法的输入=>输出阶段以及处理阶段分摊排序成本的最佳方法。这通常是有用的