数据结构中的堆的插入与删除


在这里,我们将了解如何从二叉堆数据结构中插入和删除元素。假设初始树形如下 −

插入算法

insert(heap, n, item):
Begin
   if heap is full, then exit
   else
      n := n + 1
      for i := n, i > 1, set i := i / 2 in each iteration, do
         if item <= heap[i/2], then break
         heap[i] = heap[i/2]
      done
   end if
   heap[i] := item
End

示例

假设我们要将 30 插入堆中 −


删除算法

delete(heap, n):
Begin
   if heap is empty, then exit
   else
      item := heap[1]
      last := heap[n]
      n := n – 1
      for i := 1, j := 2, j <= n, set i := j and j := j * 2, do
         if j < n, then
            if heap[j] < heap[j + 1], then j := j + 1
         end if
         if last >= heap[j], then break
         heap[i] := heap[j]
      done
   end if
   heap[i] := last
End

示例

假设我们要从最终的堆中删除 30 −

更新日期: 2020 年 8 月 10 日

5 千次浏览

开启你的 职业生涯

获取课程结业证书

开始学习
广告
© . All rights reserved.