A heap is a partially sorted binary tree. Although a heap is not completely in order, it conforms to a sorting principle: every node has a value less (for the sake of simplicity, we will assume that all orderings are from least to greatest) than either of its children. Additionally, a heap is a "complete tree" -- a complete tree is one in which there are no gaps between leaves. For instance, a tree with a root node that has only one child must have its child as the left node. More precisely, a complete tree is one that has every level filled in before adding a node to the next level, and one that has the nodes in a given level filled in from left to right, with no breaks.

Why use a heap?

A heap can be thought of as a priority queue; the most important node will always be at the top, and when removed, its replacement will be the most important. This can be useful when coding algorithms that require certain things to processed in a complete order, but when you don't want to perform a full sort or need to know anything about the rest of the nodes. For instance, a well-known algorithm for finding the shortest distance between nodes in a graph, Dijkstra's Algorithm, can be optimized by using a priority queue.

Heaps can also be used to sort data. A heap sort is O(nlogn) efficiency, though it is not the fastest possible sorting algorithm. Check out thistutorial heap sort for more information related to heap sort.

How do you implement a heap?

Although the concept of a heap is simple, the actual implementation can appear tricky. How do you remove the root node and still ensure that it is eventually replaced by the correct node? How do you add a new node to a heap and ensure that it is moved into the proper spot?

The answers to these questions are more straight forward than meets the eye, but to understand the process, let's first take a look at two operations that are used for adding and removing nodes from a heap: upheaping and downheaping.

Upheap: The upheap process is used to add a node to a heap. When you upheap a node, you compare its value to its parent node; if its value is less than its parent node, then you switch the two nodes and continue the process. Otherwise the condition is met that the parent node is less than the child node, and so you can stop the process. Once you find a parent node that is less than the node being upheaped, you know that the heap is correct--the node being upheaped is greater than its parent, and its parent is greater than its own parent, all the way up to the root.

Downheap: The downheap process is similar to the upheaping process. When you downheap a node, you compare its value with its two children. If the node is less than both of its children, it remains in place; otherwise, if it is greater than one or both of its children, then you switch it with the child of lowest value, thereby ensuring that of the three nodes being compared, the new parent node is lowest. Of course, you cannot be assured that the node being downheaped is in its proper position -- it may be greater than one or both of its new children; the downheap process must be repeated until the node is less than both of its children.

When you add a new node to a heap, you add it to the rightmost unoccupied leaf on the lowest level. Then you upheap that node until it has reached its proper position. In this way, the heap's order is maintained and the heap remains a complete tree.

Removing the root node from a heap is almost as simple: when you take the node out of the tree, you replace it with "last" node in the tree: the node on the last level and rightmost on that level.

Once the top node has been replaced, you downheap the node that was moved until it reaches its proper position. As usual, the result will be a proper heap, as it will be complete, and even if the node in the last position happens to be the greatest node in the entire heap, it will do no worse than end up back where it started.

Efficiency of a heap

Whenever you work with a heap, most of the time taken by the algorithm will be in upheaping and downheaping. As it happens, the maximum number of levels of a complete tree is log(n)+1, where n is the number of nodes in the tree. Because upheap or downheap moves an element from one level to another, the order of adding to or removing from a heap is O(logn), as you can make switches only log(n) times, or one less time than the number of levels in the tree (consider that a two level tree can have only one switch).

reference from :http://www.cprogramming.com/tutorial/computersciencetheory/heap.html

What is a heap?--reference的更多相关文章

  1. (C#) Interview Questions.

    (Note: Most are collected from Internet. 绝大部分内容来自互联网) 1. What's the difference between Hashtable and ...

  2. 11.Events

    1.A type that defines an event member allows the type (or instances of the type) to notify other obj ...

  3. OpenJDK与HashMap

    OpenJDK的非堆JDK增强提议(JDK Enhancement-Proposal,JEP)试图标准化一项基础设施,它从Java6开始,只能在HotSpot和OpenJDK内部使用.这种设施能够像管 ...

  4. MySQL :: MySQL 5.0 Reference Manual :: 14.4 The MEMORY (HEAP) Storage Engine

    MySQL :: MySQL 5.0 Reference Manual :: 14.4 The MEMORY (HEAP) Storage Engine The MEMORY (HEAP) Stora ...

  5. Java 堆内存与栈内存异同(Java Heap Memory vs Stack Memory Difference)

    --reference Java Heap Memory vs Stack Memory Difference 在数据结构中,堆和栈可以说是两种最基础的数据结构,而Java中的栈内存空间和堆内存空间有 ...

  6. Chrome-Console( Command Line API Reference)

    来源于:https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference The Comma ...

  7. CLR via C# 3rd - 05 - Primitive, Reference, and Value Types

    1. Primitive Types        Any data types the compiler directly supports are called primitive types. ...

  8. heap c++ 操作 大顶堆、小顶堆

    在C++中,虽然堆不像 vector, set 之类的有已经实现的数据结构,但是在 algorithm.h 中实现了一些相关的模板函数.下面是一些示例应用 http://www.cplusplus.c ...

  9. strong reference cycle in block

    However, because the reference is weak, the object that self points to could be deallocated while th ...

随机推荐

  1. 学习面试题Day07

    1.打印出100以内的素数 该编程题的思路大致如下: (1)完成一个判断某整数是否为素数的方法: (2)循环1--100: (3)每循环一次就判断一次,返回true则打印:package com.ex ...

  2. Explain 结果解读与实践

    Explain 结果解读与实践 基于 MySQL 5.0.67 ,存储引擎 MyISAM . 注:单独一行的"%%"及"`"表示分隔内容,就象分开“第一章”“第 ...

  3. SQL中的CASE WHEN用法

    其语法如下: 1)case vlaue when [compare-value]then reslut [when[compare-value]] then result ...] [else res ...

  4. 28、activity之间传递数据&批量传递数据

    import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android ...

  5. 017QTP 描述性编程的使用方法

    一.什么时候使用描述性编程 在测试过程中,有些界面元素是动态出现或动态变化的,在录制的时候并没有添加到对象库中 二.描述性编程的运行原理 用描述性编程编写的测试脚本在运行时,QTP会使用测试脚本中给出 ...

  6. 移动端混合型App(hybrid app)自动化测试选型与实践

    背景 公司产品的业务已经发展到了移动端,开发选型已经结束,决定使用phonegap做移动端的web应用开发平台.考虑到业务的复杂与多样,移动端的测试同样需要自动化.在网上看了很多,最终锁定了3个移动端 ...

  7. MFC控件

    控件的通知消息 控件的消息映射宏的格式大致是: ON_通知消息码(nID, memberFun) //nID参数是控件的ID,memberFun参数是消息处理函数名.例如,ON_BN_CLICKED( ...

  8. STM32 串口DMA方式接收(转)

    STM32 是一款基于ARM Cortex-M3内核的32位MCU,主频最高可达72M.最近因为要在车机上集成TPMS功能, 便开始着手STM32的开发工作,STM32F10x系列共有5个串口(USA ...

  9. 设置按钮背景图片(HTML-CSS)

    很多人提交表单时都喜欢用一个图片来作为提交按钮,大多数人可能用JS去操作表单的提交,即当用户点击这个图片时响应一个JS来提交表单.其实还有一种方法,就是直接设置SUBMIT按钮的图片背景.设置它的图片 ...

  10. 中断——中断描述符表的定义和初始化(一) (基于3.16-rc4)

    1.中断描述符表的定义(arch/x86/kernel/traps.c) gate_desc debug_idt_table[NR_VECTORS] __page_aligned_bss; 定义的描述 ...