algorithm - 通过依次插入以下元素创建一个堆

标签 algorithm data-structures language-agnostic heap

问题:

Create a heap by inserting the following elements in the order that they are given. Show the heap after each insertion and trickle. (The heap should be implemented to keep the highest key value at the top.)

5 4 6 7 9 8 1 2 3

Once you have finished creating the heap, remove each element from it. Show the heap after each removal and trickle. Indicate which element has been removed in each step.

我知道如何将元素插入堆中,但如何创建它呢?而且我真的不确定如何从堆中删除元素。

最佳答案

我将假设一个二叉堆作为我的答案,有许多不同的堆,但由于这听起来像是家庭作业并且是一个相当基本的问题,我将涵盖最基本的堆:

好吧,首先堆是空的。

然后你插入 5,所以堆现在是:

5

然后在底部插入 4。 4 比 5 小,所以我们不改变它的父级位置。堆现在是:

   5
  /
 4

然后我们在底部插入 6,在 5 的下方(始终从左到右在底部插入)。我们将新插入的节点 (6) 的值与其父节点 (5) 的值进行比较,并意识到我们必须交换它们,以免违反堆属性:

   6
  / \
 4   5

现在我们在下一个可用位置(在 4 下方)插入 7,并将它与它的父元素交换,因为 7 > 4。然后我们再次交换(或滴入),如 7 > 6 并得到:

    7
   / \
  6   5
 /
4

等等……

关于algorithm - 通过依次插入以下元素创建一个堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11175126/

相关文章:

math - float 学有问题吗?

language-agnostic - tracing generational GC 是如何判断年轻代垃圾的?

algorithm - 使用主定理

c++ - 将元素分配给数组不起作用(使用 OpenMP 的并行合并排序)

algorithm - 寻找二叉树中的最长路径

php - CakePHP 返回 find ('all' ) 使用 'id' 作为数组索引

c++ - 构建非循环依赖的最简单、最有效的数据结构是什么?

SQL 查询总重量

algorithm - 用于表示/分配文件中空闲空间的数据结构和算法

language-agnostic - 从网络应用程序与最终用户的扫描仪连接(网络/扫描仪集成)